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. 对称二叉树 #17

Open
Geekhyt opened this issue Feb 1, 2021 · 2 comments
Open

101. 对称二叉树 #17

Geekhyt opened this issue Feb 1, 2021 · 2 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 1, 2021

原题链接

递归

先明确,所谓“对称”,也就是两个树的根节点相同

  • 第一个树的左子树与第二个树的右子树镜像对称。
  • 第一个树的右子树与第二个树的左子树镜像对称。
const isSymmetric = function(root) {
    if (root === null) return true
    return isEqual(root.left, root.right) // 比较左右子树是否对称
};

const isEqual = function(left, right) {
    // 递归终止条件
    if (left === null && right === null) return true // 对称
    if (left === null || right === null) return false // 不对称
    // 比较左右子树的 root 值以及左右子树是否对称
    return left.val === right.val
        && isEqual(left.left, right.right)
        && isEqual(left.right, right.left)
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
@lywq9296
Copy link

lywq9296 commented Apr 9, 2021

这种递归的空间复杂度要怎么判断呢?

@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
@GTRgoSky
Copy link

GTRgoSky commented Mar 1, 2022

// 迭代
var isSymmetric = function(root) {
    const stack = [root.left, root.right];
    while(stack.length) {
        let curL = stack.shift();
        let curR = stack.shift();
        if (curL === curR) {
            continue;
        }
        if (!curL || !curR) {
            return false;
        }
        if (curL.val !== curR.val) {
            return false;
        }
        stack.push(curL.left, curR.right);
        stack.push(curL.right, curR.left);
    }
    return true;
};

// 递归
var isSymmetric = function(root) {
    function compare(L, R) {
        if (L === R) return true;
        if (!L || !R) return false;
        if (L.val != R.val) return false;
        return compare(L.left, R.right) && compare(L.right, R.left);
    }
    return compare(root.left, root.right);
};

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

No branches or pull requests

3 participants