0%

LeetCode: Construct Binary Tree from Inorder and Postorder Traversal

教科书的题,用递归吧

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) {
if(inorder.size()==0)
return NULL;
return foo(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
}

TreeNode* foo(vector<int>& inorder, int in_beg, int in_end, vector<int> &postorder, int post_beg,int post_end)
{
if(in_beg>in_end)
return NULL;
int last = postorder[post_end];
int mid=in_beg;
for(;inorder[mid]!=last;++mid);
int left=mid-in_beg;
int right = in_end-mid;
auto root = new TreeNode(last);
root->left = foo(inorder, in_beg, mid-1, postorder, post_beg, post_beg+left-1);
root->right = foo(inorder, mid+1, in_end, postorder, post_beg+left, post_end-1);
return root;
}
};