题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
1.不借助辅助函数,直接使用shell排序的思想,然后进行递归操作(推荐)
#include <iostream>
#include <vector>
using namespace std;
typedef struct TreeNode
{
int val;
TreeNode * left;
TreeNode * right;
TreeNode(int x)
: val(x), left(NULL), right(NULL)
{}
static void PreOrder(TreeNode *root)
{
if(root)
{
cout << root -> val;
PreOrder(root -> left);
PreOrder(root -> right);
}
}
static void InOrder(TreeNode *root)
{
if(root)
{
InOrder(root -> left);
cout << root -> val;
InOrder(root -> right);
}
}
};
class Solution
{
public:
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in)
{
if(pre.size() != in.size() || pre.size() == 0)
return NULL;
//存放前序和中序被根节点分开的序列
vector<int> left_pre, right_pre, left_in, right_in;
//创建根节点,根节点肯定是前序遍历的第一个数
TreeNode * head = new TreeNode(pre[0]);
//找到中序遍历根节点所在的位置,存放于变量gen中
int gen = 0;
for(int i = 0; i < in.size(); i++)
{
if (in[i] == pre[0])
{
gen = i;
break;
}
}
//对于中序遍历,根节点左边的节点卫浴二叉树的左边,根节点右边的节点位于二叉树的右边
//对二叉树节点进行归并
for(int i = 0; i < gen; i++)
{
left_in.push_back(in[i]);
left_pre.push_back(pre[i+1]);//前序第一个为根节点
}
for(int i = gen + 1; i < in.size(); i++)
{
right_in.push_back(in[i]);
right_pre.push_back(pre[i]);
}
//和希尔排序(shell排序)类似,取出前序和中序遍历根节点左边和右边的子树
//递归,再对其进行上述所有步骤
head -> left = reConstructBinaryTree(left_pre, left_in);
head -> right = reConstructBinaryTree(right_pre, right_in);
return head;
}
}
2.解题思路跟上面解法差不多,代码虽然简短,但是关于数组下标的确定需要较为准确
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x)
: val(x)
, left(NULL)
, right(NULL)
{}
};
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;
}
private TreeNode reConstructBinaryTree(int [] pre, int startPre, int endPre, int [] in, 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;
}
}