原文鏈接:http://www.reibang.com/p/768892e095bf
我的理解:參考建樹的方式和創(chuàng)建原型方法的方式。
二叉樹的常用遍歷為前序遍歷,中序遍歷翎朱,后序遍歷,三種遍歷方法僅僅是交換了代碼的運(yùn)行順序而已,代碼如下:
function Node(data,left,right){
this.data=data;
this.left=left;
this.right=right;
}
function Tree(){
this.root=null;
}
Tree.prototype={
//創(chuàng)建二叉樹
create: function(){
var b=new Node(2,new Node(4),new Node(5));
var c=new Node(3,new Node(6),new Node(7));
this.root=new Node(1,b,c);
},
//前序遍歷
preTravel: function(root){
if(root==null){
return;
}
console.log(root.data);
this.preTravel(root.left);
this.preTravel(root.right);
},
//中序遍歷
middleTravel: function(root){
if(root==null){
return;
}
this.middleTravel(root.left);
console.log(root.data);
this.middleTravel(root.right);
},
//后序遍歷
postTravel: function(root){
if(root==null){
return;
}
this.middleTravel(root.left);
this.middleTravel(root.right);
console.log(root.data);
}
}
一開始的時(shí)候喘漏,準(zhǔn)備為這些遍歷方法傳入一個(gè)默認(rèn)參數(shù)this.root結(jié)果發(fā)現(xiàn)會導(dǎo)致死循環(huán),最后發(fā)現(xiàn)是因?yàn)榛蹋竺鏁ndefined作為參數(shù)傳入翩迈,此時(shí)會自動使用默認(rèn)參數(shù),進(jìn)入死循環(huán)盔夜。
另外,定義原型方法時(shí)负饲,調(diào)用另一個(gè)原型方法時(shí),要在this作用域中查找喂链。
測試代碼如下:
var tree=new Tree();
tree.create();
tree.preTravel(tree.root);
tree.middleTravel(tree.root);
tree.postTravel(tree.root);