对称二叉树

LeetCode 101:递归比较两棵树是否互为镜像。

#resource / algorithm #type / howto #status / evergreen #source / leetcode #ds / tree #algo / dfs #algo / recursion

[!info] related notes 算法面试题型 MOC 二叉树基础

对称二叉树

题目

101. 对称二叉树 - 力扣(LeetCode)

思路

定义一个函数 isMirror(a, b) 判断两棵树是否镜像:

  • 两个节点都空 => true
  • 一个空一个不空 => false
  • 值相等,且 a.leftb.righta.rightb.left

代码(JavaScript)

function isMirror(a, b) {
  if (a === null && b === null) return true;
  if (a === null || b === null) return false;
  if (a.val !== b.val) return false;
  return isMirror(a.left, b.right) && isMirror(a.right, b.left);
}

var isSymmetric = function(root) {
  return isMirror(root, root);
};
创建于 2026/3/16 更新于 2026/5/27