Skip to content

No.101 对称二叉树

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

示例 1:

sample_1

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

示例 2:

sample_2

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

提示:

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

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

解题思路

实现

深度优先搜索 - dfs

js
/**
 * 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) {
  if (!root) return false;
  const isMirror = (l, r) => {
    if (!l && !r) return true;
    if (!l || !r) return false;
    return (
      l.val === r.val && isMirror(l.left, r.right) && isMirror(l.right, r.left)
    );
  };
  return isMirror(root.left, root.right);
};

广度优先搜索 - bfs

js
/**
 * 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) {
  if (!root) return false;
  const isMirror = (l, r) => {
    let stack = [];
    stack.push(l, r);
    while (stack.length) {
      l = stack.shift();
      r = stack.shift();
      if (!l && !r) continue;
      if (!l || !r || l.val !== r.val) return false;
      stack.push(l.left, r.right);
      stack.push(l.right, r.left);
    }
    return true;
  };
  return isMirror(root.left, root.right);
};