线索二叉树的生成及遍历

package tree;


/*
 * 线索二叉树
 */
public class ThreadBinaryTree<E> {
	private E[] elements = null;
	private int count = 0;
	private Node pre;//中序遍历最后一个结点或中序遍历前一个结点变量
	private Node lastLeft;//中序遍历第一个结点
	
	/*前序递归生成二叉树*/
	public Node createBinaryTree(){
		Node node = new Node();
		
		if(count >= elements.length || elements[count++] == "#"){
			return null;
		}else{
			node.element = elements[count - 1];
			node.left = createBinaryTree();
			node.right = createBinaryTree();
		}
		
		return node;
	}
	
	//中序遍历生成线索二叉树
	public Node inThreading(Node current){
		if(current != null){
			inThreading(current.left);//递归左子树线索化
			if(current.left == null){ //当前结点没有左孩子
				current.lefeTag = 1;
				current.left = pre;
			}
			
			if(pre.right == null){ //前驱没有右孩子
				pre.rightTag = 1;
				pre.right = current;
			}
			
			pre = current;//指向前一个结点
			inThreading(current.right);//递归右子树线索化
		}
		return null;
	}
	
	/*带头结点的线索二叉树*/
	public void inHeadThreading(Node head,Node root){
		if(head == null){
			head = new Node();
		}
		
		if(root == null){
			return;
		}else{
			head.left = root;//头结点的左孩子指向根结点
			head.lefeTag = 0;
			//使二叉树中序序列中的第一个结点的left和最后一个结点的right指向头结点
			//找到第一个结点
			findLastLeftNode(root);
			lastLeft.lefeTag = 1;
			lastLeft.left = head;
			
			inThreading(root);//找到最后一个结点
			head.right = pre;//头结点右孩子为空,则指向最后一个结点
			head.rightTag = 1;
			pre.right = head;//使得最后一个结点的右孩子指向头结点
			pre.rightTag = 1;
			
		}
	}


	/*线索二叉树的遍历*/
	public void inOrderTreverse(Node head){
		Node current = head.left;
		while(current != head){
			while(current.lefeTag == 0){
				current = current.left;
			}
			System.out.println(current.element);
			
			while(current.rightTag == 1 && current.right != head){
				current = current.right;
				System.out.println(current.element);
			}
			
			current = current.right;
		}
	}
	
	/*找到最左边的结点,即中序遍历的第一个结点*/
	public void findLastLeftNode(Node root){
		if(root == null){
			return;
		}
		
		Node current = root;
		while(current.left != null){
			current = current.left;
		}
		
		lastLeft = current;
	}
	
	static class Node<E>{
		int lefeTag; /*如果Tag为0则标识指向左右孩子的指针,如果为1则标识指向前驱或后继的线索*/
		int rightTag;
		Node<E> left;
		Node<E> right;
		E element;
		
		public Node(){
		}
		
		public Node(E element){
			this.element = element;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值