索引二叉樹的實現
思路:首先這里會用到一個頭結點,初始化的時候頭結點的左指針為孩子指針,不指向任何結點,右指針為索引指針指向樹節點,在進行二叉樹的中序遍歷的過程當中,pre為當前結點p的前驅結點,為了標記指針為孩子結點指針還是索引指針,這里使用如下
tagl = 1 表示為索引指針
tagl = 0表示孩子指針
首先開始編寫主方法 創建索引二叉樹createTh read
function createTrhead(bt){//參數為樹的根節點
//首先先創建一個頭結點
this.head = new Node();
//初始化頭結點的指針域
this.head.tagl = 0;//孩子結點
this.head.tagr = 1;//索引結點
//接下來先判斷根節點是否存在
if(bt == null){
//頭結點左孩子為null
this.head.tagl = 0;
this.head.left = this.head;
//頭結點的右索引指向為空
this.head.tagr = 1;
this.head.right = null;
}else{
//頭結點左孩子指向根節點
this.head.left = bt;
//pre指向頭結點
this.pre = this.head;
this.thread(bt);//開始遍歷樹
tis.head.right = this.pre;
this.pre.tagr = 1;
this.pre.right = this.head;
}
}
中序遍歷函數 thread()
function thread(bt){
//首先如果結點存在就繼續遍歷
if(bt!=null){
//遍歷左孩子
this.thread(bt.left);
//如果前驅結點右結點為null 則指向當前結點
if(this.pre.right = null){
this.pre.tagr = 1;
this.pre.right = bt;
}else{
this.pre.tagr = 0;
}
if(bt.left == null){//如果當前結點的左孩子為null 則指向前驅結點
bt.tagl = 1;
bt.left = this.pre;
}
//將當前結點作為前驅結點
this.pre = bt;
//遍歷右孩子
this.thread(bt.right);
}
}