0%

LeetCode: Construct Binary Tree from Preorder and Inorder 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
/**
* 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>& preorder, vector<int>& inorder) {
return foo(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}

TreeNode* foo(vector<int> &preorder, int pre_beg, int pre_end, vector<int>& inorder, int in_beg,int in_end)
{
if(pre_beg > pre_end)
return NULL;

int val = preorder[pre_beg];
auto root = new TreeNode(val);
int left=0;
for(;inorder[in_beg+left]!=val;++left);
root->left = foo(preorder, pre_beg+1, pre_beg+left, inorder, in_beg, in_beg+left-1);
root->right = foo(preorder, pre_beg+left+1, pre_end, inorder, in_beg+left+1, in_end);
}
};