Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.
It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less thanNode.val, and any descendant of Node.right has a value strictly greater thanNode.val.
A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.
The first preorder value is the root; a linear scan finds the first larger key and splits the left and right subtrees. \(n\le 100\) makes \(O(n^2)\) acceptable, yet each split walks the same ranges again.
A BST preorder segment still has every left-subtree key below the root and every right-subtree key above it, so the first index greater than the root can be found by binary search.
\(\textit{dfs}(i,j)\) builds a node from \(\textit{preorder}[i]\), bisects to the right-subtree start, and recurses on both sides in \(O(n\log n)\).
We design a function \(\textit{dfs}(i, j)\) to construct a binary search tree from the nodes \(\textit{preorder}[i]\) to \(\textit{preorder}[j]\). The answer is \(\textit{dfs}(0, n - 1)\).
In \(\textit{dfs}(i, j)\), we first construct the root node, which is \(\textit{preorder}[i]\). Then, we use binary search to find the first node greater than \(\textit{preorder}[i]\) and get its index \(\textit{mid}\). We set \(\textit{dfs}(i + 1, \textit{mid} - 1)\) as the left subtree of the root node and \(\textit{dfs}(\textit{mid}, j)\) as the right subtree of the root node.
Finally, we return the root node.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the array \(\textit{preorder}\).
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcbstFromPreorder(preorder[]int)*TreeNode{vardfsfunc(i,jint)*TreeNodedfs=func(i,jint)*TreeNode{ifi>j{returnnil}root:=&TreeNode{Val:preorder[i]}l,r:=i+1,j+1forl<r{mid:=(l+r)>>1ifpreorder[mid]>preorder[i]{r=mid}else{l=mid+1}}root.Left=dfs(i+1,l-1)root.Right=dfs(l,j)returnroot}returndfs(0,len(preorder)-1)}