Amazon Interview Question
Java DevelopersCountry: United States
Interview Type: In-Person
Another solution, albeit lengthier:
public static void myinorder(Node root) {
Node node = root;
Stack<Node> stack = new Stack<Node>();
stack.push(node);
while (!stack.isEmpty()) {
while ((node != null) && (node.left != null)) {
stack.push(node.left);
node = node.left;
}
System.out.print(stack.peek().value + " ");
if ((stack.peek().right == null) && (node != null) &&
(stack.peek() == node)) {
stack.pop();
node = null;
} else if ((stack.peek().right != null) && (node != null) &&
(stack.peek() != node)) {
node = stack.pop();
node = stack.peek();
}
else if ((stack.peek().right != null) && (node != null)) {
node = stack.pop().right;
stack.push(node);
}
else if ((stack.peek().right != null) && (node == null)) {
stack.push(stack.pop().right);
node = stack.peek();
}
}
}
Alternate solution:
public static void myinorder2(Node root) {
Node node = root;
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || node!=null) {
//System.out.println("Stack: " + stack);
if (node!=null) {
stack.push(node);
node = node.left;
}
else {
//System.out.println("\nStack: " + stack);
if(node!=null)
{
System.out.print(node.value+" ");
}
Node tmp = stack.pop();
//System.out.println("\nStack: " + stack);
if(tmp !=null && tmp != node)
{
System.out.print(tmp.value+" ");
}
//System.out.println("\nStack: " + stack);
if(tmp != null && tmp==node)
{
tmp=stack.pop();
System.out.print(tmp.value+" ");
}
node = tmp.right;
//System.out.println("\nNew right: " + node);
//System.out.println("Stack: " + stack);
}
}
}
Another solution, somewhat more intuitive:
public static void myinorder(Node root) {
Node node = root;
final Stack<Node> stack = new Stack<Node>();
stack.push(root);
while (!stack.isEmpty()) {
if (node == null) {
System.out.print(stack.peek().value + " ");
node = stack.pop().right;
if (node != null) {
stack.push(node);
}
} else if (node.left != null) {
stack.push(node.left);
node = node.left;
} else if (node.left == null) {
System.out.print(stack.peek().value + " ");
node = stack.pop().right;
}
}
}
Node root = new Node(5);
Node node = root;
BinarySearchTree bst = new BinarySearchTree();
bst.createBst(bst, root);
final Stack<Node> stack = new Stack<Node>();
stack.push(root);
Node trav;
trav = root;
while (!stack.isEmpty()) {
while(trav.left != null){
stack.push(trav.left);
trav = trav.left;
}
if(!stack.isEmpty()){
Node lastNode = stack.pop();
System.out.println(lastNode.value+" ");
if(lastNode.right != null){
stack.push(lastNode.right);
trav=lastNode.right;
}
}
}
1) One way is to use an additional stack.
- -- March 13, 20122) Another way that uses no stack also is: Morris Algorithm
http : // stackoverflow.com / questions / 5502916 / please-explain-morris-inorder-tree-traversal-without-using-stacks-or-recursion