classSolution{public:TreeNode*bstFromPreorder(vector<int>&preorder){TreeNode*root=newTreeNode(preorder[0]);stack<TreeNode*>stack{{root}};for(inti=1;i<preorder.size();++i){TreeNode*parent=stack.top();TreeNode*child=newTreeNode(preorder[i]);// Adjust parentwhile(!stack.empty()&&stack.top()->val<child->val)parent=stack.top(),stack.pop();// Create parent-child link according to BST propertyif(parent->val>child->val)parent->left=child;elseparent->right=child;stack.push(child);}returnroot;}};
classSolution{publicTreeNodebstFromPreorder(int[]preorder){TreeNoderoot=newTreeNode(preorder[0]);Deque<TreeNode>stack=newArrayDeque<>(Arrays.asList(root));for(inti=1;i<preorder.length;++i){TreeNodeparent=stack.peek();TreeNodechild=newTreeNode(preorder[i]);// Adjust parentwhile(!stack.isEmpty()&&stack.peek().val<child.val)parent=stack.pop();// Create parent-child link according to BST propertyif(parent.val>child.val)parent.left=child;elseparent.right=child;stack.push(child);}returnroot;}}
classSolution:defbstFromPreorder(self,preorder:List[int])->Optional[TreeNode]:root=TreeNode(preorder[0])stack=[root]foriinrange(1,len(preorder)):parent=stack[-1]child=TreeNode(preorder[i])# Adjust parentwhilestackandstack[-1].val<child.val:parent=stack.pop()# Create parent-child link according to BST propertyifparent.val>child.val:parent.left=childelse:parent.right=childstack.append(child)returnroot