forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0106.cpp
More file actions
32 lines (27 loc) · 848 Bytes
/
0106.cpp
File metadata and controls
32 lines (27 loc) · 848 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
32
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return helper(0, 0, inorder.size(), inorder, postorder);
}
private:
TreeNode* helper(int i, int j, int n, vector<int>& inorder, vector<int>& postorder) {
if (n == 0) return NULL;
TreeNode* root = new TreeNode(postorder[j + n - 1]);
if (n == 1) return root;
int k = i;
while (inorder[k] != root->val) k++;
int l = k - i;
root->left = helper(i, j, l, inorder, postorder);
root->right = helper(i + l + 1, j + l, n - l - 1, inorder, postorder);
return root;
}
};