Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

101 对称二叉树 #22

Closed
sailei1 opened this issue May 17, 2019 · 0 comments
Closed

101 对称二叉树 #22

sailei1 opened this issue May 17, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 17, 2019

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

解法:
1 左左 右右比较 左右 右左比较 (关键点)
2 递归
3 注意兼容 空值 或 只有一个节点存在时

var isSymmetric = function(root) {
    if(!root)return true;
    let result = true;  //默认对称
    let fun = (l, r) => {
        if(!l && !r){ return;} //最底层节点 不比较

        if(!l || !r){ // 一个存在时 不对称
            result = false;
            return;
        }

        if(l.val === r.val){ //相等 递归比较
            fun(l.left, r.right) // 左左 右右比较
            fun(l.right, r.left) // 左右 右左比较 
        }else{
            result = false;  //不对称
            return;
        }
    }
    fun(root.left, root.right);  
    return result;
};
@sailei1 sailei1 closed this as completed May 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant