判断二叉树是否对称
例如,二叉树 [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){
return true
}else{
return isSym(root.left,root.right)
}
};
function isSym(left,right) {
if(!left&&!right) {
return true
}
if(!left||!right){
return false
}
if(left.val!=right.val){
return false
}
return arguments.callee(left.left,right.right)&&arguments.callee(left.right,right.left)
}
二叉树遍历
var tree = {
"id": 0,
"name": "root",
"left": {
"id": 1,
"name": "Simon",
"left": {
"id": 3,
"name": "Carl",
"left": {
"id": 7,
"name": "Lee",
"left": {
"id": 11,
"name": "Fate"
}
},
"right": {
"id": 8,
"name": "Annie",
"left": {
"id": 12,
"name": "Saber"
}
}
},
"right": {
"id": 4,
"name": "Tony",
"left": {
"id": 9,
"name": "Candy"
}
}
},
"right": {
"id": 2,
"name": "right",
"left": {
"id": 5,
"name": "Carl",
},
"right": {
"id": 6,
"name": "Carl",
"right": {
"id": 10,
"name": "Kai"
}
}
}
}
// 把这个对象中所有的名字以“前序遍历”的方式全部输出到console中
function getListWithDLR(obj) {
console.log(obj.id);
if(obj.left){
getListWithDLR(obj.left);
}
if(obj.right){
getListWithDLR(obj.right);
}
}
console.log("前序遍历:");
getListWithDLR(tree);
// 把这个对象中所有的名字以“中序遍历”的方式全部输出到console中
function getListWithLDR(obj) {
if(obj.left){
getListWithLDR(obj.left);
}
console.log(obj.id);
if(obj.right){
getListWithLDR(obj.right);
}
}
console.log("中序遍历:");
getListWithLDR(tree);
// 把这个对象中所有的名字以“后序遍历”的方式全部输出到console中
function getListWithLRD(obj) {
if(obj.left){
getListWithLRD(obj.left);
}
if(obj.right){
getListWithLRD(obj.right);
}
console.log(obj.id);
}
console.log("后序遍历:");
getListWithLRD(tree);
判断两个二叉树是否相同
//严格比较二叉树,左子树和右子树必须完全一样,不可互换
function compareTree(root1, root2){
if(root1 == root2) return true;//两棵树是同一棵树
if((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false;//两棵树有一棵为null,另一棵不是null
if(root1.value != root2.value) return false;//节点的值不同
var leftBoolean = compareTree(root1.left, root2.left);//比较左子树
var rightBoolean = compareTree(root1.right, root2.right);//比较右子树
return leftBoolean && rightBoolean;//左子树和右子树必须都一样
}