题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function isSymmetrical(pRoot) { return check(pRoot, pRoot); } // 判断是否是对称的,需要比对左右两个子树,所以传入两个参数 function check(L, R) { // 叶子节点 if(!L && !R) return true; // 不含左子树或不含右子树,或者左子树和右子树不等时 就返回false if(!L || !R || L.val != R.val) return false; // 不是上面的情况就继续往下比对(递归) return check(L.left, R.right) && check(L.right, R.left); } module.exports = { isSymmetrical : isSymmetrical };
判断二叉树是否对称,是需要拿root的左右子树来比对的,这也就限定了我们不能自从一棵树自身去检查check(root),必须用两棵子树去一一比对check(root.left, root.right)。