Java实现线索二叉树
节点类:
package tree;
public class Node {
int data;
Node left;
Node right;
boolean leftIsThread;
boolean rightIsThread;
public Node(int data) {
this.data = data;
this.left = null;
this.right= null;
this.leftIsThread = false;
this.rightIsThread = false;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public boolean isLeftIsThread() {
return leftIsThread;
}
public void setLeftIsThread(boolean leftIsThread) {
this.leftIsThread = leftIsThread;
}
public boolean isRightIsThread() {
return rightIsThread;
}
public void setRightIsThread(boolean rightIsThread) {
this.rightIsThread = rightIsThread;
}
@Override
public int hashCode() {
return super.hashCode()+this.data;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Node) {
Node temp = (Node) obj;
if (temp.getData()==this.data) {
return true;
}
}
return false;
}
}
实现类:
package tree;
public class ThreadTree {
Node root;
int size;
Node pre=null;
public ThreadTree() {
this.root=null;
this.pre=null;
this.size=0;
}
public ThreadTree(int[] array) {
this.size = array.length;
this.pre = null;
root = buildTree(array, 1);
}
public Node buildTree(int[] array,int index) {
if (index>array.length) {
return null;
} else {
Node node = new Node(array[index-1]);
Node left = buildTree(array, index*2);
Node right = buildTree(array, index*2+1);
node.setLeft(left);
node.setRight(right);
return node;
}
}
public void buildThreadTree(Node root) {
if (root!=null) {
buildThreadTree(root.getLeft());
if (root.getLeft()==null) {
root.setLeftIsThread(true);
root.setLeft(pre);
}
if (pre!=null && pre.getRight()==null) {
pre.setRightIsThread(true);
pre.setRight(root);
}
pre = root;
buildThreadTree(root.getRight());
}
}
public void inThreadTree(Node root) {
if (root!=null) {
while (root!=null && !root.isLeftIsThread()) {
root=root.getLeft();
}
do {
System.out.println(root.getData());
if (root.isRightIsThread()) {
root=root.getRight();
} else {
root=root.getRight();
while (root!=null && !root.isLeftIsThread()) {
root = root.getLeft();
}
}
} while (root!=null);
}
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public void inList(Node root)
{
if (root != null)
{
inList(root.getLeft());
System.out.print(root.getData() + ",");
inList(root.getRight());
}
}
}
测试类:
package tree;
public class Test {
public static void main(String[] args) {
int[] array = {5,25,3,10,1,88,99,456,};
ThreadTree threadTree = new ThreadTree(array);
threadTree.buildThreadTree(threadTree.getRoot());
threadTree.inThreadTree(threadTree.getRoot());
}
}