对称的二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路
递归。
对称树满足:
1.根节点相同;
2.根节点左右子树相同;
3.左子树的左子树和右子树的右子树相同,左子树的右子树和右子树的左子树相同.
代码
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function isSymmetrical(pRoot)
{
// write code here
//空树 认为是对称的
if(pRoot === null) return true;
//不是空树,则判断左右子树
return help(pRoot.left,pRoot.right);
}
function help(left,right){
//左子树为空,当右子树为空时对称
if (left === null) {
return right === null;
}
//经过上一行判断出左子树不为空了,右子树为空的话不对称
if (right === null) {
return false;
}
//两个节点元素值不一样也不对称
if (left.val !== right.val) {
return false;
}
//判断子树1的右子树和子树2的左子树是否相同,子树1的左子树和子树2的右子树是否相同
}
return help(left.left, right.right) && help(left.right, right.left);
}