题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
二叉树都可以拆分成最小二叉树如
root
left right
递归的对比节点是否相等即可,对比的时候节点的外侧跟外侧对比。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function isSymmetrical(pRoot) {
// write code here
// 空树
if (!pRoot) {
return true
}
// 递归左右子树
return isEqual(pRoot.left, pRoot.right)
}
const isEqual = (leftNode, rightNode) => {
if (!leftNode && !rightNode) {
return true;
}
if ((leftNode && !rightNode) || (!leftNode && rightNode)) {
return false;
}
if (leftNode.val !== rightNode.val) {
return false;
}
// 外侧跟外侧对比,同理...
const outside = isEqual(leftNode.left, rightNode.right);
const inside = isEqual(leftNode.right, rightNode.left);
return outside && inside;
};
module.exports = {
isSymmetrical: isSymmetrical,
};


