25 - 对称二叉树

题目

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

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

说明:

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

解答

递归

var isMirror = function(node1, node2) {
  if (!node1 && !node2) {
    return true
  }
  if (!node1 || !node2) {
    return false
  }
  return (node1.val === node2.val) && isMirror(node1.left, node2.right) && isMirror(node1.right, node2.left)
}

var isSymmetric = function (root) {
  return isMirror(root, root)
};

Runtime: 64 ms, faster than 62.60% of JavaScript online submissions forSymmetric Tree.

Memory Usage: 35.6 MB, less than 48.92% of JavaScript online submissions for Symmetric Tree.

Last updated

Was this helpful?