在二叉树的很多前序,中序,后序遍历中,结点的left和right可能只用到了某一个,这就会造成很多结点的left和right属性为空,使得空间被浪费,为了充分利用这些空间,可以使用线索二叉树。让一些结点的左子树指向遍历的上一个结点,右子树指向遍历的下一个结点。
class TreeNode{
private String name;
private int no;
private TreeNode left;
private TreeNode right;
//由于类在加载过程中,能够自动给int值初始化为0,所以这里无需显式将leftType和rightType初始化为0
//如果leftType为0,表示指向左子树,如果为1,则表示指向前驱结点
private int leftType;
//如果rightType为0,表示指向右子树,如果为1,则表示指向后继结点
private int rightType;
public TreeNode(String name, int no) {
this.name = name;
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
public int getLeftType() {
return leftType;
}
public void setLeftType(int leftType) {
this.leftType = leftType;
}
public int getRightType() {
return rightType;
}
public void setRightType(int rightType) {
this.rightType = rightType;
}
@Override
public String toString() {
return "TreeNode{" +
"name='" + name + '\'' +
", no=" + no +
'}';
}
}
class ErchaTree
{
TreeNode root;
TreeNode preNode=null;
public ErchaTree(TreeNode root) {
this.root = root;
}
//这里采用中序遍历线索化
public void preThreadNode(TreeNode treeNode) {
if(treeNode==null)
{
return;
}
preThreadNode(treeNode.getLeft());
//如果左子树为空,就让它的左子树指向前驱结点
if(treeNode.getLeft()==null)
{
treeNode.setLeft(preNode);
treeNode.setLeftType(1);
}
//如果前驱结点的右子树为空,就让其指向当前结点
if(preNode!=null&&preNode.getRight()==null)
{
preNode.setRight(treeNode);
preNode.setRightType(1);
}
preNode=treeNode;
preThreadNode(treeNode.getRight());
}
public void threadList()
{
if(root==null)
{
System.out.println("二叉树为空,不能遍历!!");
}
TreeNode node=root;
while(node!=null)
{
while (node.getLeftType()==0)
{
node=node.getLeft();
}
System.out.println(node);
while (node.getRightType()==1)
{
node=node.getRight();
System.out.println(node);
}
node=node.getRight();
}
}
}
public class TreeTest2 {
public static void main(String[] args) {
TreeNode treeNode1=new TreeNode("1",1);
TreeNode treeNode2=new TreeNode("3",3);
TreeNode treeNode3=new TreeNode("6",6);
TreeNode treeNode4=new TreeNode("8",8);
TreeNode treeNode5=new TreeNode("10",10);
TreeNode treeNode6=new TreeNode("14",14);
ErchaTree erchaTree=new ErchaTree(treeNode1);
treeNode1.setLeft(treeNode2);
treeNode1.setRight(treeNode3);
treeNode2.setLeft(treeNode4);
treeNode2.setRight(treeNode5);
treeNode3.setLeft(treeNode6);
erchaTree.preThreadNode(treeNode1);
erchaTree.threadList();
}
}