Offer to prove safety [28] is inscribed: symmetrical binary tree (Java)

Please implement a function, a binary tree is used to determine not symmetrical. If a binary tree and its image, as it is symmetrical.

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

    1
   / \
  22
 / \ / \
3443
but the following [1,2,2, null, 3, null , 3] is not a mirror image:

    1
   / \
  2   2
   \   \
   3    3

 

Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:

Input: root = [1,2,2, null, 3, null, 3]
Output: false
 

limit:

0 <= the number of nodes <= 1000

Code:

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

class Solution {

    public boolean isSymmetric(TreeNode root) {

        if(root==null)

        {

            return true;

        }

        if(root.left==null&&root.right==null)

        {

            return true;

        }

        if(root.left==null||root.right==null)

        {

            return false;

        }

        return find(root.left,root.right);

    }

    public boolean find(TreeNode p,TreeNode q)

    {

        if(p==null&&q==null)

        {

            return true;

        }

        if(p==null||q==null)

        {

            return false;

        }

        if(p.val==q.val)

        {

            return find(p.left,q.right)&&find(p.right,q.left);

        }

        else

        {

            return false;

        }

    }

}

Published 275 original articles · won praise 9 · views 10000 +

Guess you like

Origin blog.csdn.net/hx1043116928/article/details/104632912