Skip to content

101. 对称二叉树 #50

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

Open
swiftwind0405 opened this issue Jan 10, 2021 · 0 comments
Open

101. 对称二叉树 #50

swiftwind0405 opened this issue Jan 10, 2021 · 0 comments

Comments

@swiftwind0405
Copy link
Owner

swiftwind0405 commented Jan 10, 2021

方法一:递归(分而治之)

解题思想:

  • 转化为:左右子树是否是镜像
  • 分解为:树1的左子树和树2的右子树是否镜像,树1的右子树和树2的左子树是否镜像

代码:

var isSymmetric = function(root) {
    if (!root) return true;

    const isMirror = (l, r) => {
        if (!l && !r) return true;
        if (l && r && (l.val === r.val) &&
            isMirror(l.left, r.right) && 
            isMirror(l.right, r.left)
        ) {
            return true;
        }
        return false;
    } 

    return isMirror(root.left, root.right);
};

复杂度分析:

  • 时间复杂度:O(n),访问所有的节点;
  • 空间复杂度:O(n),递归的堆栈,堆栈的深度为二叉树的高度,在最差情况下,就是节点的个数。

方法二:迭代

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant