-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst_from_inorder_and_postorder.cpp
30 lines (28 loc) · 1.07 KB
/
bst_from_inorder_and_postorder.cpp
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
/**
* 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* build(vector<int>& preorder, vector<int>& inorder, int& rootIdx, int left, int right) {
if (left > right) return NULL;
int pivot = left; // find the root from inorder
while(inorder[pivot] != preorder[rootIdx]) pivot++;
rootIdx++;
TreeNode* newNode = new TreeNode(inorder[pivot]);
newNode->left = build(preorder, inorder, rootIdx, left, pivot-1);
newNode->right = build(preorder, inorder, rootIdx, pivot+1, right);
return newNode;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int rootIdx = 0;
return build(preorder, inorder, rootIdx, 0, inorder.size()-1);
}
};