Quite easy question i suppose- Emulate inorder BST tree traversal without using recursion.
Anonymous
For the BST (or any binary tree) inorder traversal without recursion let's use a stack. 1. Put a node on the stack. 2. Peek a node from a stack (without removing it). 3.a If a left node exists and not visited yet, put it on the stack and continue. 3.b if a left node exists and already visited OR left node does not exist, pop the current node and print it. 4 if a right node exists and not visited yet, put it on the stack and continue. public static void traverse(final Node root) { if (root == null) { return; } Stack stack = new Stack(); stack.push(root); Set visited = new HashSet(); while (!stack.isEmpty()) { Node curr = stack.peek(); if (curr.left != null) { if (!visited.contains(curr.left)) { stack.push(curr.left); continue; } else { stack.pop(); System.out.print(curr.data + " "); visited.add(curr); } } else { stack.pop(); System.out.print(curr.data + " "); visited.add(curr); } if (curr.right != null) { if (!visited.contains(curr.right)) { stack.push(curr.right); continue; } } } }
Check out your Company Bowl for anonymous work chats.