输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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) { return reConstructBinaryTree(pre,0,pre.size()-1,vin,0,vin.size()-1); } TreeNode* reConstructBinaryTree(vector<int> pre,int p1,int q1,vector<int> vin,int p2,int q2) { if(p1>q1){ return NULL; } int idx; for(idx=p2;idx<=q2;idx++){ if(vin[idx]==pre[p1]){ break; } } TreeNode* node=new TreeNode(pre[p1]); node->left=reConstructBinaryTree(pre,p1+1,p1+1+idx-1-p2,vin,p2,idx-1); node->right=reConstructBinaryTree(pre,q1-(q2-idx-1),q1,vin,idx+1,q2); return node; } };