。。。有点笨蛋但好懂的解法
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function isSymmetrical(pRoot)
{
// write code here
//空树---对称
if(!pRoot) return true;
//只有根节点的树---对称
if(pRoot.left == null && pRoot.right == null) return true;
//如果左右子树二缺一 --- 不对称
if(pRoot.left && pRoot.right){
//如果左右两树根的值不相等,不用往下判断了 --- 不对称
if(pRoot.left.val !== pRoot.right.val) return false;
}else return false;
//中序遍历--将节点值放入数组
this.inorder = function(root,arr){
if(arr === undefined){
arr = [];
}
if(!root) return null;
this.inorder(root.left,arr);
arr.push(root.val);
this.inorder(root.right,arr);
return arr;
};
//遍历生成数组
var leftArr = this.inorder(pRoot.left,[]);
var rightArr = this.inorder(pRoot.right,[]);
//翻转后的左子树数组和右子树数组对比
//数值相同---对称
if(leftArr.reverse().toString() == rightArr.toString()) return true;
return false;
}
module.exports = {
isSymmetrical : isSymmetrical
};



京公网安备 11010502036488号