Based on the preorder traversal definition for a BST, the first element in the slice is always coming from the root node, we can split the rest elements into two parts from the element which is no less than the root node for child nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcbstFromPreorder(preorder []int) *TreeNode { var root *TreeNode length := len(preorder) if length > 0 { root = &TreeNode{} root.Val = preorder[0] i := 1 for i < length { if preorder[i] >= root.Val { break } i++ } root.Left = bstFromPreorder(preorder[1:i]) root.Right = bstFromPreorder(preorder[i:]) } return root }
The last element in postorder slice is the root node, with this information, we can split inorder to a left subtree and a right subtree. Since now we know the amount of nodes in the left subtree, we can go back to split the postorder list into two.
With the second element in preorder slice, we can split postorder slice into two sub slices. With this information we can go back to split the preorder slice into two sub slices with the same sizes.
With the idea from the above one, since Suppose b is a copy of a with the value val appended to it. , it means b can only be the root node or part of right subtree based on the tree construction rule.