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.)
It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]


 
Constraints:

1 <= preorder.length <= 100
1 <= preorder[i] <= 10^8
The values of preorder are distinct.

Difficulty: interview

Starter code:

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        

Solutions:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        # time O(n); space O(n)
        vals = deque(preorder)
        
        def build(min_val, max_val):
            if vals and min_val < vals[0] < max_val:
                val = vals.popleft()
                node = TreeNode(val)
                node.left = build(min_val, val)
                node.right = build(val, max_val)
                
                return node
        
        return build(float('-inf'), float('inf'))

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if not preorder:
            return None
        root = TreeNode(preorder[0])
        if len(preorder) == 1:
            return root
        # left = [i for i in preorder if i < root.val]
        # right = [i for i in preorder if i > root.val]
        ind = len(preorder)
        for i, j in enumerate(preorder):
            if j > root.val:
                ind = i
                break
        root.left = self.bstFromPreorder(preorder[1:ind])
        root.right = self.bstFromPreorder(preorder[ind:])
        
        return root

class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        root = TreeNode(preorder[0])
        stack = [root]
        for val in preorder[1:]:
            node = TreeNode(val)
            if val < stack[-1].val:
                stack[-1].left = node
            else:
                while stack and stack[-1].val < val:
                    last = stack.pop()
                last.right = node
            stack.append(node)
        return root

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        self.inorder = sorted(preorder)
        self.preorder = preorder[::-1]
        n = len(preorder)
        self.m = { val:i for i, val in enumerate(self.inorder)}
        lo, hi = 0, n-1
        return self.dfs(lo, hi)
        
    def dfs(self, lo, hi):
        if lo > hi: return None
        
        val = self.preorder.pop()
        root = TreeNode(val)
        mid = self.m[val]
        root.left = self.dfs(lo, mid-1)
        root.right = self.dfs(mid+1, hi)
        
        return root

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        root = node = TreeNode(preorder[0])
        stack = []
        
        for n in preorder[1:]:
            if n < node.val:
                node.left = TreeNode(n)
                stack.append(node)
                node = node.left
            else:
                while stack and stack[-1].val < n:
                    node = stack.pop()
                node.right = TreeNode(n)
                node = node.right
        return root
                    


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if not preorder or len(preorder) == 0:
            return None
        inorder = sorted(preorder)
        root = TreeNode(preorder[0])
        leftLen = inorder.index(root.val)
        root.left = self.bstFromPreorder(preorder[1: 1+leftLen])
        root.right = self.bstFromPreorder(preorder[1+leftLen:])
        return root
        


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def bstFromPreorder(self, A: List[int]) -> TreeNode:
        A.reverse()
        
        def build(lower = -math.inf, upper = math.inf):
            if not A or A[-1] < lower or A[-1] > upper:
                return None
            
            root = TreeNode(A.pop())
            root.left = build(lower, root.val)
            root.right = build(root.val, upper)
            return root
        return build()

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if not preorder:
            return
        root = TreeNode(preorder[0])
        i = 1
        while i<len(preorder) and preorder[i]<=root.val:
            i += 1
        
        root.left = self.bstFromPreorder(preorder[1:i])
        root.right = self.bstFromPreorder(preorder[i:])
        
        return root

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        
        if len(preorder) == 0:
            return None
        
        return self.helper(preorder,0,len(preorder))
        
    def helper(self,preorder,start,end):
        # print(start,end,preorder[start:end])
        if start >= end:
            return None
        
        split = start + 1
        root = TreeNode(preorder[start])
        
        while split < end and preorder[start] > preorder[split]:
            split+=1
        
        root.left = self.helper(preorder,start + 1,split)
        root.right = self.helper(preorder,split,end)
        return root

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def get_small(self, arr: List[int], idx: int, min_val: float) -> int:
        for i in range(idx+1, len(arr)):
            if arr[i] < arr[idx] and arr[i] >= min_val:
                return i
            
        return -1
    
    def get_big(self, arr: List[int], idx: int, max_val: float) -> int:
        for i in range(idx+1, len(arr)):
            if arr[i] >= arr[idx] and arr[i] < max_val:
                return i
            
        return -1
        
    def helper(self, preorder: List[int], idx: int, min_val: float, max_val: float) -> TreeNode:
        if idx == -1:
            return None
        
        root = TreeNode(preorder[idx])
        left = self.get_small(preorder, idx, min_val)
        right = self.get_big(preorder, idx, max_val)
        
        root.left = self.helper(preorder, left, min_val, preorder[idx])
        root.right = self.helper(preorder, right, preorder[idx], max_val)
        
        return root
        
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        return self.helper(preorder, 0, float(\"-inf\"), float(\"inf\"))
        

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        def construct(preorder):
            if len(preorder) == 0:
                return None
            root = TreeNode(preorder[0])
            #   开始分裂
            idx = 0
            while idx < len(preorder):
                if preorder[idx] > preorder[0]:
                    break
                idx += 1
            root.left  = construct(preorder[1:idx])
            root.right = construct(preorder[idx:])
            return root
        root = construct(preorder)
        return root


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        # 
        # minHeap | O(NlogN) | ----- 40 ms (50.65%) / 14.3 MB (5.13%)
        # ------------------------------------------------------------------------------------------------
        if not preorder:
            return None
        root = TreeNode(val=preorder[0])
        parents = [(root.val, root)]
        heapq.heapify(parents)
        for idx in range(1, len(preorder)):
            num = preorder[idx]
            node = TreeNode(val=num)
            tmp = None
            while parents and parents[0][0] < num:
                _, tmp = heapq.heappop(parents)
            if tmp:
                tmp.right = node
            elif not tmp and parents:
                parents[0][1].left = node
            heapq.heappush(parents, (num, node))   
        return root