题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
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> in) {
if(pre.size() == 0)
return NULL;
TreeNode* head = new TreeNode(pre[0]);
vector<int> left_pre, right_pre, left_in, right_in;
int gen;
//找到根节点在中序遍历中的下标
for(int i = 0; i < in.size(); i++)
{
if(in[i] == pre[0])
{
gen = i;
break;
}
}
//中序遍历根节点左边的排序是左子树的中序遍历
for(int i = 0; i < gen; i++)
{
left_pre.push_back(pre[i + 1]);//相对应前序遍历的i+1,因为前序遍历左边比中序遍历多
//一个根节点的访问。
left_in.push_back(in[i]);
}
//同理右边是右子树的中序遍历,相对应前序遍历的i
for(int i = gen + 1; i < in.size(); i++)
{
right_pre.push_back(pre[i]);
right_in.push_back(in[i]);
}
//归并
head -> left = reConstructBinaryTree(left_pre, left_in);
head -> right = reConstructBinaryTree(right_pre, right_in);
return head;
}
};
已知后续遍历和中序遍历的情况
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> last,vector<int> in) {
if(last.size() == 0)
return NULL;
TreeNode* head = new TreeNode(last[last.size() - 1]);
vector<int> left_last, right_last, left_in, right_in;
int gen;
for(int i = 0; i < in.size(); i++)
{
if(in[i] == last[last.size() - 1])
{
gen = i;
break;
}
}
for(int i = 0; i < gen; i++)
{
left_last.push_back(last[i]);
left_in.push_back(in[i]);
}
for(int i = gen + 1; i < in.size(); i++)
{
right_last.push_back(last[i - 1]);
right_in.push_back(in[i]);
}
head -> left = reConstructBinaryTree(left_last, left_in);
head -> right = reConstructBinaryTree(right_last, right_in);
return head;
}
};
题目的其他解法:
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;
}
}