Skip to content
On this page

101. 对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false

提示:
树中节点数目在范围 [1, 1000] 内
-100 <= Node.val <= 100

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

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSymmetric = function (root) {
  var isSameTree = function (p, q) {
    if (!p && !q) return true
    if ((!p && q) || (p && !q)) return false
    if (p.val === q.val) {
      return isSameTree(p.left, q.right) && isSameTree(p.right, q.left)
    } else {
      return false
    }
  }
  return isSameTree(root.left, root.right)
}

// test
function TreeNode(val, left, right) {
  this.val = val === undefined ? 0 : val
  this.left = left === undefined ? null : left
  this.right = right === undefined ? null : right
}

var n1 = new TreeNode(1)
var n2 = new TreeNode(2)
var n3 = new TreeNode(2)
var n4 = new TreeNode(3)
var n5 = new TreeNode(4)
var n6 = new TreeNode(4)
var n7 = new TreeNode(3)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
n3.left = n6
n3.right = n7

console.log(isSymmetric(n1))