中序线索二叉树(Java)

来源:互联网 发布:mac团灭 编辑:程序博客网 时间:2024/06/13 08:28
package com.tree;import java.util.Scanner;class BiTree {    BiTree lchild;    BiTree rchild;    String data;    int ltag;    int rtag;}
public class CreatBiTree {    static Scanner scanner = new Scanner(System.in);    // test case: A B C # # # D E # F # # #    //                A B D H # K # # # E # # C F I # # # G # J # #    //                A B D H # # I # #  E J  # # # C F # #  G # #    /**     * 构建二叉树     * 从键盘输入节点(输入时,节点之间要用空格隔开)     * @param root     * @return     */    static BiTree createBiTree(BiTree p) {        BiTree root;        String data = scanner.next();        if (data.equals("#")) {            return null;        } else {            root = new BiTree();            root.data = data;            root.lchild = createBiTree(root.lchild);            if (root.lchild!=null) {                root.ltag=0;            }            root.rchild = createBiTree(root.rchild);            if (root.rchild!=null) {                root.rtag=0;            }            return root;        }    }
 //建立头结点,中序线索二叉树    public static void InOrderThread_Head(BiTree T, BiTree t)    {        //T=new BiTree();//新建了一个对象,所以如果不返回,pTree的值仍然为null        T.rchild=T;        T.rtag=1;        //pre = T;        T.lchild = t;        //第一步        T.ltag = 0;        InThreading(t);         //找到最后一个结点        pre.rchild = T;        //第四步        pre.rtag = 1;        T.rchild = pre;      //第二步        //return T;    }
 static BiTree pre;    public static void InThreading(BiTree pTree){        if (pTree!=null) {                  InThreading(pTree.lchild);            if (pTree.lchild==null) {                pTree.ltag=1;                pTree.lchild=pre;            }            if (pre!=null && pre.rchild==null) {                                    pre.rtag=1;                    pre.rchild=pTree;            }            pre=pTree;            InThreading(pTree.rchild);        }    }
    //遍历线索到的二叉树    public static void  InOrderTraverse_THr(BiTree T) {        BiTree pBiTree;        pBiTree=T.lchild;        while (pBiTree!=T) {            while (pBiTree.ltag==0) {                pBiTree=pBiTree.lchild;                 }            System.out.println(pBiTree.data);            while (pBiTree.rtag==1 && pBiTree.rchild!=T) {                pBiTree=pBiTree.rchild;                System.out.println(pBiTree.data);            }            pBiTree=pBiTree.rchild;        }    }
    public static void main(String[] args) {        //BiTree pTree=null;        BiTree qTree=new BiTree();//仔细看,弄懂不同        BiTree root = null;        root = createBiTree(root);       // pTree= InOrderThread_Head(pTree, root);//为什么不返回,pTree的值仍然为null?????       InOrderThread_Head(qTree, root);        InOrderTraverse_THr(qTree);                }}
0 0
原创粉丝点击