题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
示例1
输入
{8,6,6,5,7,7,5}返回值
true
输入
{8,6,9,5,7,7,5}返回值
false
思路
思路:首先根节点以及其左右子树,左子树的左子树和右子树的右子树相同
左子树的右子树和右子树的左子树相同即可,采用递归
代码
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function isSymmetrical(pRoot)
{
// write code here
if(pRoot == null) return true;
return justify(pRoot.left,pRoot.right)
}
function justify(left,right) {
if(left == null) return right == null;
//if(right == null) return false;
if(right == null) return left == null;
if(left.val!=right.val) return false;
return justify(left.left,right.right) && justify(left.right,right.left)
}
运行环境:Javascript_V8
运行时间:10ms
占用内存:5288KB