101 title: symmetrical binary tree

One. Problem Description

Given a binary tree, check if it is mirror-symmetrical.

For example, a binary tree [1,2,2,3,4,4,3] is symmetric.

     1

    /  \

  2     2

 / \     / \

3  4  4  3

However, the following [1,2,2, null, 3, null, 3] is not a mirror image:

    1

   / \

  2   2

   \   \

   3    3

two. Problem-solving ideas

The title ideas: + recursive depth search elements the way to solve it.

Step a: recursive function (node ​​1 p, nodes 2 q). And comparing the value of the node p and q are equal.

Step 2: When equal, recursively, the p-right subtree left subtree and q combination recursive recursive function, the left subtree right subtree of p and q in combination a function recursively, repeating steps a .

Step Three: If all returns true, the final returns true, otherwise false.

three. Results of the

When execution: 0 ms, defeated 100.00% of users in all java submission

Memory consumption: 37.7 MB, defeated 67.38% of all users in java submission

four. Java code

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)
            return true;
       return treeN(root.left,root.right);
    }
    
    public boolean treeN(TreeNode p,TreeNode q){
        if(p==null&&q==null)
        {
            return true;
        }else if(p==null||q==null)
        {
            return false;
        }
        
        if(p.val==q.val)
        {
            if(treeN(p.left, q.right)&&treeN(p.right,q.left)) return true;
        }else
        {
            return false;
         }
         return false;
    }
}

 

Guess you like

Origin www.cnblogs.com/xiaobaidashu/p/11800042.html