101、对称二叉树
题目描述:
js
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree递归思路
两个树要对称需要具备以下两个条件:
- 1、它们的根节点具有相同的值。
- 2、每个树的右子树和另一个树的左子树对称。
代码
js
/**
* @param {TreeNode} root
* @return {number[]}
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
const n1 = new TreeNode(1);
const n2 = new TreeNode(2);
const n3 = new TreeNode(2);
const n4 = new TreeNode(3);
const n5 = new TreeNode(4);
const n6 = new TreeNode(4);
const n7 = new TreeNode(3);
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
var isSymmetric = function (root) {
const help = (left, right) => {
if (!left && !right) return true; //左右子树都为空也算对称
if (left && right) {
// 左右子树都存在时比较他们值是否相等,再递归调用下去。
return (
left.val === right.val &&
help(left.left, right.right) && //左子树的左节点是否等于右子树的右节点
help(left.right, right.left)
); //左子树的右节点是否等于右子树的左节点
}
return false; //如果左右子树一个存在一个不存在 不对称
};
return !root || help(root.left, root.right); //根节点 root 为空也是属于对称的 不为空就调用 help 函数开始判断
};
console.log(isSymmetric(n1)); //true要点
二叉树的题目,大多数可以用递归来做,递归主要确定 2 点。
- 递归的子问题
- 递归的结束条件
russ