劍指offer上的題目
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode *root=Create(pre,0,pre.size()-1,vin,0,vin.size()-1);
return root;
}
private:
TreeNode* Create(vector<int> pre,int startPre,int endPre,vector<int> vin,int startIn,int endIn)
{
if(startPre>endPre||startIn>endIn)
return NULL;
TreeNode *root=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;i++)
if(pre[startPre]==vin[i]){
root->left=Create(pre,startPre+1,startPre+i-startIn,vin,startIn,i-1);
root->right=Create(pre,i-startIn+startPre+1,endPre,vin,i+1,endIn);
}
return root;
}
};