Original title link here: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
topic:
Return the root node of a binary search tree that matches the given preorder
traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left
has a value <
node.val
, and any descendant of node.right
has a value >
node.val
. Also recall that a preorder traversal displays the value of the node
first, then traverses node.left
, then traverses node.right
.)
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Note:
1 <= preorder.length <= 100
- The values of
preorder
are distinct.
answer:
The first element should be root. As BST, root left subtree should be smaller than root value, right subtree should be bigger than root value.
Could use root value as pivot and find out array corresponding to left subtree, also array corresponding to right subtree.
Time Complexity: O(nlogn). Each level of tree, it takes O(n) time, tree height should be O(logn).
Space: O(logn).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public TreeNode bstFromPreorder(int[] preorder) { 12 if(preorder == null || preorder.length == 0){ 13 return null; 14 } 15 16 return dfs(preorder, 0, preorder.length-1); 17 } 18 19 private TreeNode dfs(int[] preorder, int l, int r){ 20 if(l > r){ 21 return null; 22 } 23 24 TreeNode root = new TreeNode(preorder[l]); 25 int biggerIndex = l+1; 26 while(biggerIndex<=r && preorder[biggerIndex]<preorder[l]){ 27 biggerIndex++; 28 } 29 30 root.left = dfs(preorder, l+1, biggerIndex-1); 31 root.right = dfs(preorder, biggerIndex, r); 32 return root; 33 } 34 }