对称二叉树
LeetCode 101:递归比较两棵树是否互为镜像。
#resource / algorithm
#type / howto
#status / evergreen
#source / leetcode
#ds / tree
#algo / dfs
#algo / recursion
[!info] related notes 算法面试题型 MOC 二叉树基础
对称二叉树
题目
思路
定义一个函数 isMirror(a, b) 判断两棵树是否镜像:
- 两个节点都空 => true
- 一个空一个不空 => false
- 值相等,且
a.left对b.right、a.right对b.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);
};