索引二叉樹實現


索引二叉樹的實現

思路:首先這里會用到一個頭結點,初始化的時候頭結點的左指針為孩子指針,不指向任何結點,右指針為索引指針指向樹節點,在進行二叉樹的中序遍歷的過程當中,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);
    }
}
總結:在進行遍歷這可樹的時候遍歷所經過的結點的順序就是中序遍歷的順序,這個過程當中,pre和p中要么pre右指針為null要么p的左指針為null 這樣就可以將這些結點鏈接成一個二叉鏈表了,最后中序遍歷的結點的尾指針指向頭結點,形成一個二叉樹的中序遍歷循環單鏈表


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM