geeksforgeeks:Construct a Binary Search Tree from given postorder (A243)

Given postorder traversal of a binary search tree, construct the BST.
For example, if the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned.
     10
   /   \
  5     40
 /  \      \
1    7      50
TreeNode constructTree(int[] arr)
Solution:
input is a integer array, contains leaf key. The null node isn't existed in input array, it's hard to determine whether child node is null with only one postindex. so we set a range for every node. 1)Initial the range as Integer.min_value and Integer.max_value. so the root node is definitely in the range, create the node.
2) compare the node value with the range, if key is in the range, create the node. otherwise return null
3) construct the right subtree, set the range as {root.val, max}.
4) construct the left subtree, set the range as {min, root.val}.
take 50 for example.
when it construct right subtree, the postindex is point at 5, because 5 is not in the range (50,max), it return null.
when it construct the left subtree, the postindex is still point at 5, because 5 is not in range (40,50), so left subtree is null.
 //because there is not null element in input array, so it's hard to determine the leaf of subtree whose child node is null.
    TreeNode constructTree(int[] arr)  
    { 
        int[] postIndex = new int[1];
        int n = arr.length;
        postIndex[0] = n -1;
        return constructTreeUtil(arr,postIndex,Integer.MIN_VALUE, Integer.MAX_VALUE); 
    } 
    public TreeNode constructTreeUtil(int[] arr, int[] postIndex, int min, int max) {
     int index = postIndex[0];
     if(index < 0) return null;
     TreeNode res = null;
     int key = arr[index];
     if(key > min && key < max) {
         res = new TreeNode(key);
         postIndex[0]--;
         res.right = constructTreeUtil(arr,postIndex , key, max);
         res.left = constructTreeUtil(arr,postIndex , min, key);
     }else {
      System.out.println(key);
     }
     return res;
    }


Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal