码迷,mamicode.com
首页 > 其他好文 > 详细

construct bst from preorder

时间:2018-08-17 00:39:44      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:structure   div   color   divide   value   complex   put   for   int   

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.
             10
           /              /        {5, 1, 7}       {40, 50}

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








public int idx = 0;
private TreeNode constructBST(int[] pre) {
    return constructBSTfromPreorder(pre, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private TreeNode constructBSTfromPreorder(int[] pre, int min, int max) {
    if (idx >= pre.length){
      return null;
    }
    if (pre[idx] <= min || pre[idx] >= max) {
      return null;
    }
    TreeNode root = new TreeNode(pre[idx++]);
    root.left = constructBSTfromPreorder(pre, min, root.val);
    root.right = constructBSTfromPreorder(pre, root.val, max);
    return root;
}

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

 

construct bst from preorder

标签:structure   div   color   divide   value   complex   put   for   int   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9490862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!