版权声明:敲一敲看一看 https://blog.csdn.net/idealhunting/article/details/84977835
题目描述
思路:通过pre[0]的确立根结点,然后in中找到根结点,得出左右子树结点。创建数组preL,preR,inL,inR,然后递归调用算法。
平时练PAT都是全局的,这次开始看见题目还是懵了,知道要创建数组递归调用,但是感觉不太好,因为以前遇到的都是全局的数组,开销就没那么大,结果还是无可避免的得创数组,递归。。。。
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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* reConstructBinaryTree(vector<int>pre,vector<int>in){
int inLen=in.size();
if(inLen==0)return nullptr;
vector<int> preL,preR,inL,inR;
TreeNode* head=new TreeNode(pre[0]);
int k=0;//记录根结点位置
for(;k<inLen;k++){
if(in[k]==pre[0])break;
}
for(int i=0;i<k;i++){
inL.push_back(in[i]);
preL.push_back(pre[i+1]);
}
for(int i=k+1;i<inLen;i++){
inR.push_back(in[i]);
preR.push_back(pre[i]);
}
head->left=reConstructBinaryTree(preL,inL);
head->right=reConstructBinaryTree(preR,inR);
return head;
}
};
牛客高赞:这写法和PAT做题时是一样的23333。//没有接口,咱可以自己造,学到了~~
链接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6
来源:牛客网
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
//前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,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(in[i]==pre[startPre]){
root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
break;
}
return root;
}
}