# 1008

Oct 13th, 2021
645
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /**
2.  * Definition for a binary tree node.
3.  * struct TreeNode {
4.  *     int val;
5.  *     TreeNode *left;
6.  *     TreeNode *right;
7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10.  * };
11.  */
12. class Solution {
13. public:
14.     TreeNode* bstFromPreorder(vector<int>& preorder) {
15.         int n = preorder.size();
16.         if(!n) return NULL;
17.
18.         deque<TreeNode*> q;
19.         TreeNode *root = new TreeNode(preorder[0]);
20.         q.push_back(root);
21.
22.         for(int i=1; i<n; i++){
23.             TreeNode *node = q.back();
24.             TreeNode *child = new TreeNode(preorder[i]);
25.
26.             while(!q.empty() && q.back()->val < child->val){
27.                 node = q.back();
28.                 q.pop_back();
29.             }
30.
31.             if(node->val < child->val)
32.                 node->right = child;
33.             else
34.                 node->left = child;
35.
36.             q.push_back(child);
37.         }
38.         return root;
39.     }
40. };
RAW Paste Data