Construct BST from preorder list

Construct BST from preorder list

https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversa/



https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/Construct%20BST%20from%20preorder%20list.java


10, 5, 1, 7, 40, 50
0.  1.  2.3  4.   5. 



这个题就是用 区间来判断 当前这个值 是不是在这个范围之内的, 如果是那就新开一个node, 
give it a value nums[index]. 如果不是的话, 直接返回null。 不要忘了index++, 为了下次的值

总之, 这个recursion,很像 validate bst 那个做法


 the given traversal is {10, 5, 1, 7, 40, 50}, 
then the output should be root of following tree.
//      10(0)
//    /       \
//   5 (1)    40(4)
//  /      \     \
// 1 (2)   7(3)   50(5)

10 的区间是 (min, max)
  
5 的区间是(min, 10)
40 的区间是 (10, max) 
  
括号里的树是 index


public int index = 0;
private TreeNode constructBST(int[] nums){
  return preorder(nums, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

private TreeNode preorder(int[] nums, int min, int max){
  if(index > nums.length) return null;
  if(nums[index] <= min || nums[index] >= max){
    return null;
  }
  
  TreeNode root = new TreeNode(nums[index++]);
  root.left = preorder(nums, min, root.val);
  root.right = preorder(nums, root.val, max);
  return root;
}

 

construct bst from preorder 

https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversa/




https://algorithms.tutorialhorizon.com/construct-binary-search-tree-from-a-given-preorder-traversal-using-recursion/


Method 1 ( O(n^2) time complexity )
The first element of preorder traversal is always root. We first construct the root. Then we find the index of first element which is greater than root. Let the index be ‘i’. The values between root and ‘i’ will be part of left subtree, and the values between ‘i+1’ and ‘n-1’ will be part of right subtree. Divide given pre[] at index “i” and recur for left and right sub-trees.
For example in {10, 5, 1, 7, 40, 50}, 10 is the first element, so we make it root. Now we look for the first element greater than 10, we find 40. So we know the structure of BST is as following.
           /    \
          /      \
  {5, 1, 7}       {40, 50}

We recursively follow above steps for subarrays {5, 1, 7} and {40, 50}, and get the complete tree.


// 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

 

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

posted on 2018-08-09 18:26  猪猪&#128055;  阅读(131)  评论(0)    收藏  举报

导航