Offer prove safety fluent series - symmetrical binary tree

28 is inscribed: symmetrical binary tree

I. Description of the problem

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

    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }

The figure, A is not symmetrical BC
Here Insert Picture Description

Second, the problem analysis

Direct comparison to the root, we focus on analysis about sub-tree.
Here Insert Picture Description

Symmetrical binary tree to meet the above example, it can be seen, the left and right subtrees also happens to be a mirror image of two binary tree
Here Insert Picture Description
when comparing we
can use a left subtree of the parent node -> the left node -> the right node traversal mode - 657
of right subtree of the parent node can be used -> right node -> the left node traversal mode - 657
according to the comparison sequence.

Third, questions

   public boolean isSymmetrical(TreeNode pRoot){
        if(pRoot==null) {
            return true; //根结点为null时,认为是对称二叉树
        }
        return isEqual(pRoot.left,pRoot.right);
    }

    private boolean isEqual(TreeNode pRoot1,TreeNode pRoot2){
        if(pRoot1==null && pRoot2==null) {
            return true;
        }
        if(pRoot1==null || pRoot2==null) {
            return false;
        }
        return pRoot1.val==pRoot2.val
                && isEqual(pRoot1.left, pRoot2.right)
                && isEqual(pRoot1.right, pRoot2.left);
    }
Published 151 original articles · won praise 3197 · Views 450,000 +

Guess you like

Origin blog.csdn.net/qq_42322103/article/details/104094911