跳到主要内容

101. [✔][E]对称二叉树

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

示例 1:

img

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

示例 2:

img

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

提示:

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

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


题解:

// @ts-ignore
function isSymmetric(root: TreeNode | null): boolean {

// @ts-ignore
const isMirror = (left: TreeNode | null, right: TreeNode | null): boolean => {
if (left === null && right === null) {
return true;
}

if (left === null || right === null) {
return false;
}

return left.val === right.val
&& isMirror(left.left, right.right)
&& isMirror(left.right, right.left);

}

return isMirror(root, root);
};
// @lc code=end