描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解法
code
/**
* 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) {
int sz = pre.size();
if (sz == 0){
return NULL;
}
return TreeBuildByPreIn(pre, in, 0, 0, sz);
}
struct TreeNode* TreeBuildByPreIn(vector<int> pre, vector<int> in, int index_pre, int index_in, int sz){
if(sz == 0){
return NULL;
}
TreeNode* rt = new TreeNode(pre[index_pre]);
int p;
for(int i=0; i<sz; ++i){
if(pre[index_pre] == in[index_in+i]){
p = index_in+i;
break;
}
}
int lsz = p - index_in;
int rsz = sz - lsz - 1;
rt->left = TreeBuildByPreIn(pre, in, index_pre+1, index_in, lsz);
rt->right = TreeBuildByPreIn(pre, in, index_pre+lsz+1, p+1, rsz);
return rt;
}
};