根据前序与中序构造二叉树

根据前序遍历与后序遍历,构造二叉树

题目链接

思路:递归即可。

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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//pre是前序遍历 vin是中序遍历
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size()==0) return nullptr;
TreeNode* root = new TreeNode(pre[0]);
int i = 0;
for(;i<=pre.size();i++){
if (pre[0] == vin[i]) break;
}
vector< int > lowin(vin.begin(),vin.begin()+i);
vector< int > highin(vin.begin()+i+1,vin.end());
vector< int > lowpre(pre.begin()+1,pre.begin()+lowin.size()+1);
vector< int > highpre(pre.begin()+lowin.size()+1,pre.end());
root->left = reConstructBinaryTree(lowpre,lowin);
root->right = reConstructBinaryTree(highpre,highin);
return root;
}
};