意外行为 - 查找二叉树是否对称的递归方法

时间:2014-12-30 04:52:08

标签: recursion binary-tree mirror

问题:给定二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。

解决方案:

public class Solution {
  boolean bl = false , br = false , result = false;
    public boolean isSymmetric(TreeNode root) {

        if(root == null)
          return true;

        result = Equals(root.left, root.right);
        return result;
    }

    public boolean Equals(TreeNode left, TreeNode right){
        boolean result = false;
        if(left == null && right == null) 
            return true;

        if(left != null && right != null){

            if(left.val == right.val)
                {
                    bl = Equals(left.left, right.right);
                    br = Equals(left.right, right.left);
                    result = br&&bl ;                                //Issue.

                    //result = Equals(left.left, right.right) && Equals(left.right, right.left);
                }


        return result;
    }
}

嗨大家,在函数equals中,我试图在检查他们的父节点是否相等但是它不起作用之后,在左右子树上单独调用Equals函数。

if (left.val == right.val) {
    bl = Equals(left.left, right.right);
    br = Equals(left.right, right.left);
    result = br && bl;
}

令人惊讶的是,如果我使用下面的代码执行相同的操作,那就可以了。

if (left.val == right.val) {
    result = Equals(left.left, right.right) && Equals(left.right, right.left);
}

请帮助我理解这种行为。感谢

0 个答案:

没有答案