输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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:
struct TreeNode* findnode(vector<int> pre,int L1,int R1,vector<int> in,int L2,int R2){
if(R1-L1<0)
return NULL;
struct TreeNode *Root=new TreeNode(pre[0]);
int root=pre[L1];
Root->val=root;
if(R1==L1){
Root->left=NULL;
Root->right=NULL;
return Root;
}
int L;
for(int i=L2;i<=R2;i++){
if(in[i]==root){
L=i;
break;
}
}
Root->left=findnode(pre,L1+1,L1+L-L2,in,L2,L-1);
Root->right=findnode(pre,L1+L-L2+1,R1,in,L+1,R2);
return Root;
}
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
int n=pre.size(),m=in.size();
if(n==0)
return NULL;
struct TreeNode *root;
root=findnode(pre,0,n-1,in,0,m-1);
return root;
}
};
“`