-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy path1008-kir3i.cpp
More file actions
31 lines (29 loc) · 833 Bytes
/
1008-kir3i.cpp
File metadata and controls
31 lines (29 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
*/
class Solution {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
int sz = preorder.size();
TreeNode *root = new TreeNode(preorder[0]);
for (int i = 1; i < sz; i++) {
pushNode(root, new TreeNode(preorder[i]));
}
return root;
}
void pushNode(TreeNode *root, TreeNode *child) {
if (child->val < root->val)
if (root->left) pushNode(root->left, child);
else root->left = child;
else
if (root->right) pushNode(root->right, child);
else root->right = child;
}
};