zoukankan      html  css  js  c++  java
  • 索引二叉树实现

    索引二叉树的实现

    思路:首先这里会用到一个头结点,初始化的时候头结点的左指针为孩子指针,不指向任何结点,右指针为索引指针指向树节点,在进行二叉树的中序遍历的过程当中,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 这样就可以将这些结点链接成一个二叉链表了,最后中序遍历的结点的尾指针指向头结点,形成一个二叉树的中序遍历循环单链表
  • 相关阅读:
    6-Python爬虫-分布式爬虫/Redis
    ES 查询时 排序报错(fielddata is disabled on text fileds by default ... )解决方法
    Intellij Idea webstorm 激活
    Intellij Idea 配置jdk
    java 获取(格式化)日期格式
    js 跳转 XSS漏洞 预防
    CSS去掉背景颜色
    js对象无法当成参数传递 解决方法
    Elasticsearch java api
    java多条件查询SQL语句拼接的小技巧
  • 原文地址:https://www.cnblogs.com/webcyh/p/11470865.html
Copyright © 2011-2022 走看看