1008.cpp (680B)
1 class Solution { 2 public: 3 TreeNode *bstFromPreorder(vector<int> &preorder) { 4 int index = 0; 5 TreeNode *root = new TreeNode(preorder[index++]); 6 stack<TreeNode *> st; 7 st.push(root); 8 while (index < preorder.size()) { 9 int val = preorder[index++]; 10 if (val < st.top()->val) { 11 st.push(st.top()->left = new TreeNode(val)); 12 } else { 13 TreeNode *crnt = nullptr; 14 while (!st.empty() && val > st.top()->val) 15 crnt = st.top(), st.pop(); 16 st.push(crnt->right = new TreeNode(val)); 17 } 18 } 19 return root; 20 } 21 };