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.
``````

Solution:

``````func bstFromPreorder(preorder []int) *TreeNode {
lenP := len(preorder)

root := &TreeNode{Val: preorder[0]}
list := []*TreeNode{}
list = append(list, root)
for i:= 1; i < lenP; i++ {
node := &TreeNode{Val: preorder[i]}
pre := list[len(list) - 1]
if pre.Val > node.Val {
pre.Left = node
list = append(list, node)
continue
}

for list[len(list)-1].Val < node.Val {
if(len(list)> 1) {
pre = (list[len(list)-1])
list = list[0:len(list)-1]
}else {
pre = list[0]
list = list[0:0]
break
}
}
pre.Right = node;
list = append(list, node)
}
return root
}``````