-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode106.cpp
More file actions
28 lines (21 loc) · 935 Bytes
/
leetcode106.cpp
File metadata and controls
28 lines (21 loc) · 935 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
class Solution {
int postIndex;
public:
TreeNode* buildTreeHelper(vector<int>& inorder, vector<int>& postorder, int inStart, int inEnd, unordered_map<int,int>& inMap) {
if(inStart > inEnd) return nullptr;
int rootVal = postorder[postIndex--];
TreeNode* root = new TreeNode(rootVal);
int inIndex = inMap[rootVal];
// IMPORTANT: build right subtree first
root->right = buildTreeHelper(inorder, postorder, inIndex + 1, inEnd, inMap);
root->left = buildTreeHelper(inorder, postorder, inStart, inIndex - 1, inMap);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
postIndex = postorder.size() - 1;
unordered_map<int,int> inMap;
for(int i = 0; i < inorder.size(); i++)
inMap[inorder[i]] = i;
return buildTreeHelper(inorder, postorder, 0, inorder.size() - 1, inMap);
}
};