import java.util.Stack;
import java.util.concurrent.LinkedBlockingDeque;
public class TreeTraversal {
public Node createTree() throws InterruptedException{
LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>();
Node root = new Node();
int idx = 0;
root.setData(idx);
queue.add(root);
while(true){
if(queue.isEmpty())break;
Node curr = queue.pop();
idx++;
Node left = new Node();
left.setData(idx);
curr.setLeft(left);
Node right = new Node();
idx++;
right.setData(idx);
curr.setRight(right);
queue.putLast(left);
queue.putLast(right);
System.out.println("curr="+curr.getData()
+" left="+curr.getLeft().getData()
+" right="+curr.getRight().getData());
if(idx>10)break;
}
return root;
}
public void rootPrivilege(Node root) throws InterruptedException{
LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>();
queue.putLast(root);
while(true){
if(queue.isEmpty())break;
Node node = queue.pop();
System.out.println(node.getData());
if(node.getLeft()!=null)queue.putLast(node.getLeft());
if(node.getRight()!=null)queue.putLast(node.getRight());
}
}
public void rootLast(Node root) throws InterruptedException{
Stack<Node> stack = new Stack<Node>();
stack.push(root);
LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>();
while(true){
if(stack.isEmpty())break;
Node curr = stack.pop();
queue.putFirst(curr);
if(curr.getLeft()!=null)stack.push(curr.getLeft());
if(curr.getRight()!=null)stack.push(curr.getRight());
}
while(!queue.isEmpty()){
System.out.println(queue.pop().getData());
}
}
private void rootMiddleLeftTillEnd(Stack<Node> stack, Node curr){
stack.push(curr);
while(curr.getLeft()!=null){
stack.push(curr.getLeft());
curr = curr.getLeft();
}
}
public void rootMiddle(Node root) throws InterruptedException{
Stack<Node> stack = new Stack<Node>();
rootMiddleLeftTillEnd(stack, root);
while(true){
if(stack.isEmpty())break;
Node curr = stack.pop();
System.out.println(curr.getData());
if(curr.getRight()!=null)rootMiddleLeftTillEnd(stack, curr.getRight());
}
}
public static void main(String args[]){
TreeTraversal t = new TreeTraversal();
try {
Node root = t.createTree();
t.rootMiddle(root);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}