function BTNode(data) {
this.data = data;
}
BTNode.prototype.setLC = function(node){
this.leftchild = node;
}
BTNode.prototype.setRC = function(node){
this.rightchild = node;
}
//前序遍历
function preOrderTraverse(Btree){
if(Btree==null){
return;
}
console.info(Btree.data);
preOrderTraverse(Btree.leftchild);
preOrderTraverse(Btree.rightchild);
}
//中序遍历
function inOrderTraberse(Btree){
if(Btree==null){
return;
}
inOrderTraberse(Btree.leftchild);
console.info(Btree.data);
inOrderTraberse(Btree.rightchild);
}
//后序遍历
function postOrderTraberse(Btree){
if(Btree==null){
return;
}
postOrderTraberse(Btree.leftchild);
postOrderTraberse(Btree.rightchild);
console.info(Btree.data);
}
var nodeA = new BTNode('A');
var nodeB = new BTNode('B');
var nodeC = new BTNode('C');
var nodeD = new BTNode('D');
var nodeE = new BTNode('E');
var nodeF = new BTNode('F');
var nodeG = new BTNode('G');
var nodeH = new BTNode('H');
var nodeI = new BTNode('I');
var nodeJ = new BTNode('J');
var nodeK = new BTNode('K');
nodeA.setLC(nodeB);
nodeA.setRC(nodeC);
nodeB.setLC(nodeD);
nodeB.setRC(nodeE);
nodeD.setLC(nodeH);
nodeH.setRC(nodeK);
nodeC.setLC(nodeF);
nodeC.setRC(nodeG);
nodeF.setLC(nodeI);
nodeG.setRC(nodeJ);
console.info('前序遍历');
preOrderTraverse(nodeA);
console.info('中序遍历');
inOrderTraberse(nodeA);
console.info('后序遍历');
postOrderTraberse(nodeA);
结果显而易见
前序遍历
ABDHKECFIGJ
中序遍历
HKDBEAIFCGJ
后序遍历
KHDEBIFJGCA
网友评论