前一篇博客写了,根据先序、中序求后序和后序、中序求前序,但是没有重建二叉树,这一篇主要写怎么根据遍历结果重建二叉树,上一篇博客地址:
https://blog.csdn.net/weixin_42949480/article/details/105447729
直接插代码:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/*
测试二叉树形状:
1
2 3
4 5 6
*/
/*
先序遍历序列为 1 2 4 5 3 6
中序遍历序列为 4 2 5 1 6 3
后续遍历序列为 4 5 2 6 3 1
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//根据前序中序重建二叉树
TreeNode* reConstructBinaryTree0(vector<int> pre, vector<int> mid)
{
int nodeSize = mid.size();
if (nodeSize == 0)
return NULL;
vector<int> leftPre, leftMid, rightPre, rightMid;
TreeNode* phead = new TreeNode(pre[0]); //第一个当是根节点
int rootPos = 0; //根节点在中序遍历中的位置
for (int i = 0; i < nodeSize; i++)
{
if (mid[i] == pre[0])
{
rootPos = i;
break;
}
}
for (int i = 0; i < nodeSize; i++)
{
if (i < rootPos)
{
leftMid.push_back(mid[i]);
leftPre.push_back(pre[i + 1]);
}
else if (i > rootPos)
{
rightMid.push_back(mid[i]);
rightPre.push_back(pre[i]);
}
}
phead->left = reConstructBinaryTree0(leftPre, leftMid);
phead->right = reConstructBinaryTree0(rightPre, rightMid);
return phead;
}
//根据后序中序重建二叉树
TreeNode* reConstructBinaryTree1(vector<int> back, vector<int> mid)
{
int nodeSize = mid.size();
if (nodeSize == 0)
return NULL;
vector<int> leftBack, leftMid, rightBack, rightMid;
TreeNode* phead = new TreeNode(back[nodeSize-1]); //最后一个是根节点
int rootPos = 0; //根节点在中序遍历中的位置
for (int i = 0; i < nodeSize; i++)
{
if (mid[i] == back[nodeSize - 1])
{
rootPos = i;
break;
}
}
for (int i = 0; i < nodeSize; i++)
{
if (i < rootPos)
{
leftMid.push_back(mid[i]);
leftBack.push_back(back[i]);
}
else if (i > rootPos)
{
rightMid.push_back(mid[i]);
rightBack.push_back(back[i-1]);
}
}
phead->left = reConstructBinaryTree1(leftBack, leftMid);
phead->right = reConstructBinaryTree1(rightBack, rightMid);
return phead;
}
//打印后续遍历顺序
void printBackNodeValue(TreeNode* root)
{
if (!root) {
return;
}
printBackNodeValue(root->left);
printBackNodeValue(root->right);
cout << root->val << " ";
}
//打印前续遍历顺序
void printPreNodeValue(TreeNode* root)
{
if (!root) {
return;
}
cout << root->val << " ";
printPreNodeValue(root->left);
printPreNodeValue(root->right);
}
int main()
{
vector<int> preVec0{ 1, 2, 4, 5, 3, 6 };
vector<int> midVec0{ 4, 2, 5, 1, 6, 3 };
cout << "先序遍历序列为 1 2 4 5 3 6" << endl;
cout << "中序遍历序列为 4 2 5 1 6 3" << endl;
TreeNode* root0 = reConstructBinaryTree0(preVec0, midVec0);
cout << "后续遍历序列为 ";
printBackNodeValue(root0);
cout << endl<<"—————————————"<<endl;
vector<int> backVec1{ 4, 5, 2, 6, 3, 1 };
vector<int> midVec1{ 4, 2, 5, 1, 6, 3 };
cout << "后序遍历序列为 4 5 2 6 3 1" << endl;
cout << "中序遍历序列为 4 2 5 1 6 3" << endl;
TreeNode* root1 = reConstructBinaryTree1(backVec1, midVec1);
cout << "前续遍历序列为 ";
printPreNodeValue(root1);
cout << endl;
system("pause");
}