题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
AC代码
#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;
}
} TreeNode;
TreeNode *fun(int *pre, int *mid, int len)
{
if (len == 0)
return NULL;
int index;
TreeNode *p = new TreeNode(pre[0]);
for (int i = 0; i < len; i++)
{
if (pre[0] == mid[i])
{
index = i;
break;
}
}
p->left = fun(pre + 1, mid, index);
p->right = fun(pre + index + 1, mid + index + 1, len - index - 1);
return p;
}
// TreeNode *head;
class Solution
{
public:
TreeNode *reConstructBinaryTree(vector<int> pre, vector<int> vin)
{
if (pre.size() == 0 || vin.size() == 0)
return nullptr;
int *pre_tree = new int[pre.size()];
int *vin_tree = new int[vin.size()];
for (int i = 0; i < pre.size(); i++)
{
pre_tree[i] = pre[i];
vin_tree[i] = vin[i];
}
return fun(pre_tree, vin_tree, pre.size());
// return fun(pre, vin, 0, pre.size(), 0,vin.size());
}
};
void print(TreeNode *root)
{ //后序遍历
if (root != NULL)
{
print(root->left);
print(root->right);
cout << root->val;
}
}
int main()
{
Solution a;
int Tree_pre[8] = {1,2,4,7,3,5,6,8};
int Tree_vin[8] = {4,7,2,1,5,3,8,6};
vector<int>pre(Tree_pre, Tree_pre+8); //用数组初始化向量
vector<int>vin(Tree_vin, Tree_vin+8);
TreeNode *p = a.reConstructBinaryTree(pre, vin);
print(p);
return 0;
}
总结
- 感觉这个oj好麻烦,写个函数的参数都要严格要求
- 对于二叉树的构建这只是个简单的题目=-=,好像没啥总结的。。
来源:CSDN
作者:chenchenxiaojian
链接:https://blog.csdn.net/weixin_42100456/article/details/103916254