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;
}
}
}
线索二叉树的生成及遍历
最新推荐文章于 2024-07-29 08:47:18 发布