Given preorder traversal of a binary search tree, construct the BST.
For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree.
10 / 5 40 / 1 7 50
We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time.
1. Create an empty stack.
2. Make the first value as root. Push it to the stack.
3. Keep on popping while the stack is not empty and the next value is greater than stack’s top value. Make this value as the right child of the last popped node. Push the new node to the stack.
4. If the next value is less than the stack’s top value, make this value as the left child of the stack’s top node. Push the new node to the stack.
5. Repeat steps 2 and 3 until there are items remaining in pre[].
This can be done in constant time with two way:
1 //Construct BST from given preorder traversal 2 class BSTNode{ 3 public TreeNode tree; 4 public Integer min; 5 public Integer max; 6 public BSTNode(TreeNode tree, int min, int max){ 7 this.tree = tree; 8 this.min = min; 9 this.max = max; 10 } 11 } 12 13 14 //Iterative: 15 public static TreeNode preorderToBST(int[] preorder){ 16 if(preorder == null || preorder.length == 0) return null; 17 LinkedList<BSTNode> stack = new LinkedList<BSTNode>(); 18 int len = preorder.length; 19 TreeNode result = new TreeNode(preorder[0]); 20 BSTNode root = new BSTNode(result, Integer.MIN_VALUE, Integer.MAX_VALUE); 21 stack.push(root); 22 for(int i = 1; i < len; i ++){ 23 TreeNode cur = new TreeNode(preorder[i]); 24 while(!stack.isEmpty()){ 25 BSTNode tmp = stack.peek(); 26 if(tmp.min < cur.val && cur.val < tmp.tree.val){//left child 27 tmp.tree.left = cur; 28 stack.push(new BSTNode(cur, tmp.min, tmp.tree.val)); 29 break; 30 }else if(tmp.tree.val < cur.val && cur.val < tmp.max){//right child 31 tmp.tree.right = cur; 32 stack.push(new BSTNode(cur, tmp.tree.val, tmp.max)); 33 break; 34 }else if(cur.val > tmp.max){//not this treenode's child 35 stack.pop(); 36 }else{ 37 System.out.println("Error happens! This is not a valid preorder traersal array. "); 38 return null; 39 } 40 } 41 } 42 return result; 43 } 44 45 46 //Recrusive: 47 public int pos = 0; 48 public static TreeNode preorderToBST(int[] preorder, int min, int max){ 49 if(preorder == null || preorder.length == 0 || pos == preorder.length) return null; 50 int val = preorder[pos]; 51 if(min < val && val < max){ 52 TreeNode root = new TreeNode(val); 53 pos ++; 54 root.left = preorderToBST(preorder, min, val); 55 root.right = preorderToBST(preorder, val, max); 56 } 57 }