题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
方案:在二叉树的前序遍历序列中,第一个数字总是树的根节点的值;
在二叉树的中序遍历序列中,根节点的值在序列的中间,根节点左侧的值为左子树的节点值,根节点右侧的值为右子树的节点值。
Eg:前序遍历序列:{1,2,4,3,5,6},中序遍历序列{4,2,1,5,3,6}
方案1与方案2只是递归结束条件不同;如下表格表示的是左子树的递归结束步骤。
方案1:
i | start_pre | end_pre | start_vin | end_vin |
| 0 | 5 | 0 | 5 |
2 | 1 | 2 | 0 | 1 |
1 | 2 | 2 | 0 | 0 |
0 | 3 | 2 | 0 | -1 |
方案2:
start_pre | end_pre | start_vin | end_vin | left_tmp | left_length |
0 | 5 | 0 | 5 | 2 | 2 |
1 | 2 | 0 | 1 | 1 | 1 |
2 | 2 | 0 | 0 | 0 | 0 |
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
方案1:
class Solution {
public:
TreeNode* constructCore(vector<int> pre, vector<int> vin, int start_pre, int end_pre, int start_vin, int end_vin){
TreeNode* root = new TreeNode(pre[start_pre]);
//递归结束的条件
if (start_pre > end_pre || start_vin > end_vin){
return NULL;
}
for (int i = start_vin; i<=end_vin; i++){
if (vin[i] == pre[start_pre]){
root->left = constructCore(pre, vin, start_pre + 1, start_pre + i - start_vin, start_vin, i - 1);
root->right = constructCore(pre, vin, start_pre + i - start_vin + 1, end_pre, i + 1, end_vin);
break;
}
}
return root;
}
方案2:
class Solution {
public:
TreeNode* constructCore(vector<int> pre, vector<int> vin, int start_pre, int end_pre, int start_vin, int end_vin){
TreeNode* root = new TreeNode(pre[start_pre]);
//递归结束条件
if (start_pre == end_pre && start_vin == end_vin && pre[start_pre] == vin[start_pre]){
return root;
}
int left_tmp = 0;
for (int i = start_vin; i <= end_vin; i++){
if (vin[i] == pre[start_pre]){
left_tmp = i;
break;
}
}
int left_length = left_tmp - start_vin;
if(left_length >0){
root->left=constructCore(pre,vin,start_pre+1,start_pre+left_length,start_vin,left_tmp-1);
}
if(left_length < end_pre - start_pre){
root->right=constructCore(pre,vin,start_pre+left_length+1,end_pre,left_tmp+1,end_vin)
}
return root;
}
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
if (pre.size() <= 0 || vin.size() <= 0){
return NULL;
}
return constructCore(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1);
}
};
参考链接:
https://blog.csdn.net/qianhangkang/article/details/79527572
《剑指offer》P62