import java.util.Stack;
/**
* Iterative Preorder Traversal Using Stack
* @author PRATEEK
*/
class IterativePreorder {
public static void main
(String[] args
) {
Node root = new Node(12);
root.left = new Node(8);
root.left.left = new Node(6);
root.left.right = new Node(10);
root.right = new Node(16);
root.right.left = new Node(14);
root.right.right = new Node(20);
IterativePreorder obj = new IterativePreorder();
obj.iterativePreorder(root);
}
/**
* Iterative Preorder Traversal Using Stack
* @param root: root of tree
*/
public void iterativePreorder(Node root)
{
Stack<Node> stack = new Stack<Node>();
if(root!=null)
stack.push(root);
while(!stack.isEmpty())
{
Node item = stack.pop();
System.
out.
print(item
+ "\t"); if(item.right!=null)
stack.push(item.right);
if(item.left!=null)
stack.push(item.left);
}
}
}
class Node implements Comparable<Node> {
public Node left;
public int data;
public Node right;
public Node(int val)
{
this.data=val;
}
@Override
public int compareTo(Node that) {
return this.data - that.data ;
}
@Override
return this.data + "";
}
}
CmltcG9ydCBqYXZhLnV0aWwuU3RhY2s7CgogCiAKLyoqCiAqIEl0ZXJhdGl2ZSBQcmVvcmRlciBUcmF2ZXJzYWwgVXNpbmcgU3RhY2sKICogQGF1dGhvciBQUkFURUVLCiAqLwpjbGFzcyBJdGVyYXRpdmVQcmVvcmRlciB7CgoJcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewoKCQlOb2RlIHJvb3QgPSBuZXcgTm9kZSgxMik7CgkJcm9vdC5sZWZ0ID0gbmV3IE5vZGUoOCk7CgkJcm9vdC5sZWZ0LmxlZnQgPSBuZXcgTm9kZSg2KTsKCQlyb290LmxlZnQucmlnaHQgPSBuZXcgTm9kZSgxMCk7CgoJCXJvb3QucmlnaHQgPSBuZXcgTm9kZSgxNik7CgkJcm9vdC5yaWdodC5sZWZ0ID0gbmV3IE5vZGUoMTQpOwoJCXJvb3QucmlnaHQucmlnaHQgPSBuZXcgTm9kZSgyMCk7CgoJCUl0ZXJhdGl2ZVByZW9yZGVyIG9iaiA9IG5ldyBJdGVyYXRpdmVQc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