索引二叉树的实现

思路:首先这里会用到一个头结点,初始化的时候头结点的左指针为孩子指针,不指向任何结点,右指针为索引指针指向树节点,在进行二叉树的中序遍历的过程当中,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 这样就可以将这些结点链接成一个二叉链表了,最后中序遍历的结点的尾指针指向头结点,形成一个二叉树的中序遍历循环单链表
posted on 2019-09-06 08:32  渐凸强、啊哈  阅读(835)  评论(0编辑  收藏  举报