Threaded Binary Tree
package ds.threadedTree;
class ThreadedNode {
int tData;
ThreadedNode left, right;
boolean leftThread, rightThread;
public ThreadedNode() {
}
public ThreadedNode(int tData, ThreadedNode left, ThreadedNode right,
boolean leftThread, boolean rightThread) {
this.tData = tData;
this.left = left;
this.right = right;
this.leftThread = leftThread;
this.rightThread = rightThread;
}
public ThreadedNode(boolean leftThread, boolean rightThread) {
this.tData = Integer.MAX_VALUE;
this.left = this;
this.right = this;
this.leftThread = leftThread;
this.rightThread = rightThread;
}
}
class ThreadedBSTree {
private ThreadedNode root;
public ThreadedBSTree() {
root = new ThreadedNode(true, false);
}
/*
* public int insert(int tData){ ThreadedNode newNode = findNode(root,
* tData); // if(newNode==null)
*
* }
*/
public ThreadedNode findNode(ThreadedNode current, int tData) {
if (current.tData < tData) {
if (current.rightThread)
return current;
return findNode(current.right, tData);
} else if (current.tData > tData) {
if (current.leftThread)
return current;
return findNode(current.left, tData);
} else
return null;
}
public void insert(int ele) {
ThreadedNode ptr = findNode(root, ele);
/** element already present **/
if (ptr == null)
return;
if (ptr.tData < ele) {
ThreadedNode nptr = new ThreadedNode(ele, ptr, ptr.right, true,
true);
ptr.right = nptr;
ptr.rightThread = false;
} else {
ThreadedNode nptr = new ThreadedNode(ele, ptr.left, ptr, true, true);
ptr.left = nptr;
ptr.leftThread = false;
}
}
public void inOrder() {
ThreadedNode temp = root;
for (;;) {
temp = insucc(temp);
if (temp == root)
break;
System.out.print(temp.tData + " ");
}
}
public ThreadedNode insucc(ThreadedNode tree) {
ThreadedNode temp;
temp = tree.right;
if (!tree.rightThread)
while (!temp.leftThread)
temp = temp.left;
return temp;
}
}
public class ThreadedTree {
public static void main(String args[]) {
ThreadedBSTree threadedBSTree = new ThreadedBSTree();
threadedBSTree.insert(12);
threadedBSTree.insert(9);
threadedBSTree.insert(22);
threadedBSTree.insert(16);
threadedBSTree.insert(32);
threadedBSTree.insert(30);
threadedBSTree.insert(42);
threadedBSTree.inOrder();
}
}
No comments:
Post a Comment