问题描述
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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
代码
对称二叉树:当前节点值相等,且左子树和右子树是对称的状态。
var isSymmetric = function(root) {
if(root == null) return true;
return isSame(root.left, root.right);
};
function isSame(A, B){
if(A == null && B == null) return true;
if(A == null || B == null) return false;
return A.val == B.val && isSame(A.left, B.right) && isSame(A.right, B.left);
}