标签:
节点类。
因为不会使用java的enum。所以RTag和LTag就使用String凑活用吧。
package struct; public class BiThrNode { private String data; private BiThrNode lchild; private BiThrNode rchild; private String LTag; //Thread或null private String RTag; public String getData() { return data; } public void setData(String data) { this.data = data; } public BiThrNode getLchild() { return lchild; } public void setLchild(BiThrNode lchild) { this.lchild = lchild; } public BiThrNode getRchild() { return rchild; } public void setRchild(BiThrNode rchild) { this.rchild = rchild; } public String getLTag() { return LTag; } public void setLTag(String lTag) { LTag = lTag; } public String getRTag() { return RTag; } public void setRTag(String rTag) { RTag = rTag; } }
二叉树线索化及中序遍历的方法。
以及演示代码:
package demo; import struct.BiThrNode; public class BiThrTree { //pre为全局变量 public static BiThrNode pre; //中序遍历线索化 public static void InThreading(BiThrNode p){ if(p!=null){ InThreading(p.getLchild()); if(p.getLchild()==null){ p.setLTag("Thread"); p.setLchild(pre); } if(pre.getRchild()==null){ pre.setRTag("Thread"); pre.setRchild(p); } pre=p; InThreading(p.getRchild()); } } public static void InOrderTraverse_Thr(BiThrNode T){ BiThrNode p; p = T.getLchild(); //p指向根节点 while(p != T){ while(p.getLTag() == null){ p = p.getLchild(); } System.out.print(p.getData() + " "); while(p.getRTag()=="Thread"){ p = p.getRchild(); System.out.println(p.getData() + " "); } p = p.getRchild(); } } public static void main(String[] args){ BiThrNode ba = new BiThrNode(); BiThrNode bb = new BiThrNode(); BiThrNode bc = new BiThrNode(); BiThrNode bd = new BiThrNode(); BiThrNode be = new BiThrNode(); BiThrNode bf = new BiThrNode(); BiThrNode head = new BiThrNode(); ba.setLchild(bb); ba.setRchild(bc); bb.setLchild(bd); bb.setRchild(be); bc.setRchild(bf); head.setLchild(ba); ba.setData("A"); bb.setData("B"); bc.setData("C"); bd.setData("D"); be.setData("E"); bf.setData("F"); BiThrNode p = ba; pre = p; InThreading(p); p = head; InOrderTraverse_Thr(p); } }
标签:
原文地址:http://www.cnblogs.com/rixiang/p/4640851.html