题目:输入某二叉树前序中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中不包含重复数字。例如 输入前序遍历{1,2,4,7,5,6,8} 和中序遍历{4,7,2,1,5,3,8,6}
以下是我用c++的实现
#include<iostream>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
return MyConstruct(pre,0,pre.size()-1,in,0,in.size()-1);
}
struct TreeNode* MyConstruct(vector<int> pre,int pre_begin,int pre_end,vector<int> in ,int in_begin,int in_end){
if(pre_begin > pre_end || in_begin > in_end) return NULL;
int root_val = pre[pre_begin];
struct TreeNode * root = TreeNode(pre[pre_begin]);
for(int i =in_begin;i<=in_end;i++){
if(in[i] ==root_val){
root->left = MyConstruct(pre,pre_begin+1,pre_begin+i-in_begin,in,in_begin,i-1);
root->right = MyConstruct(pre,pre_begin+i-in_begin+1,pre_end,in,i+1,in_end);
break;
}
}
return root;
}
};