let arr
=[5,1,2,6,5]
function Node(val
){
this.val
=val
;
this.left
=null;
this.right
=null;
this.addLeft=function(node
){
this.left
=node
;
};
this.addRight=function(node
){
this.right
=node
;
}
}
let root
=new Node(arr
.shift());
arr
.map(item
=>{
addNode(root
,item
);
})
function addNode(node
,val
){
if(node
==null) return;
if(val
<=node
.val
){
if(node
.left
){
addNode(node
.left
,val
);
} else{
node
.left
=new Node(val
);
}
} else {
if(node
.right
){
addNode(node
.right
,val
);
} else {
node
.right
=new Node(val
);
}
}
}
function beginCon(node
){
if(node
==null)return;
console
.log(node
.val
);
beginCon(node
.left
);
beginCon(node
.right
);
}
function centerCon(node
){
if(node
==null)return;
beginCon(node
.left
);
console
.log(node
.val
);
beginCon(node
.right
);
}
function getHeight(node
){
if(node
==null)return 0;
else {
let left
= getHeight(node
.left
);
let right
= getHeight(node
.right
);
let deep
= left
;
if(deep
<right
)deep
=right
;
return deep
+1;
}
}
function getMax(node
){
if(node
==null) return -1;
let left
=getMax(node
.left
);
let right
=getMax(node
.right
);
let mid
= node
.val
;
let max
=left
;
if(right
>max
){
max
=right
;
}
if(mid
>max
){
max
=mid
;
}
return max
;
}
beginCon(root
);
console
.log('---------------');
centerCon(root
);
console
.log('---------------');
console
.log('高度:',getHeight(root
))
console
.log('最大值:',getMax(root
))
转载请注明原文地址:https://tech.qufami.com/read-19220.html