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 #55

Open
sl1673495 opened this issue Jun 5, 2020 · 0 comments
Open

对称二叉树-101 #55

sl1673495 opened this issue Jun 5, 2020 · 0 comments
Labels
DFS 深度优先遍历 二叉树 待复习 看题解或者做出来很艰难的,需要回顾。

Comments

@sl1673495
Copy link
Owner

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

例如,二叉树 [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

进阶:

你可以运用递归和迭代两种方法解决这个问题吗?

思路

当一个二叉树对称时,说明它的左子树的左节点和右子树的右节点对称,并且左子树的右节点和右子树的左节点也对称。

根节点 root 可以同时当做最初的左节点和右节点,可以简化这个问题的判断。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSymmetric = function (root) {
    if (!root) return true
    let helper = (left, right) => {
        if (!left && !right) {
            return true
        }
        if (!left || !right) {
            return false
        }
        if (left.val === right.val) {
            return helper(left.left, right.right) && helper(left.right, right.left)
        } else {
            return false
        }
    }
    return helper(root, root)
};
@sl1673495 sl1673495 added DFS 深度优先遍历 二叉树 待复习 看题解或者做出来很艰难的,需要回顾。 labels Jun 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 深度优先遍历 二叉树 待复习 看题解或者做出来很艰难的,需要回顾。
Projects
None yet
Development

No branches or pull requests

1 participant