给定一个树的前序和中序遍历结构,重建二叉树,并输出后序和层序遍历
大体思想就是不断从前序中按照顺序在中序中寻找相同的树,然后分开二叉树,分为左子树和右子树,依旧是不断递归。构建好二叉树后,后序和层序就简单了。
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
vector<int> cengxu;
vector<int> post;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* reConstructBinaryTree(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 = reConstructBinaryTree(leftPre, leftMid);
phead->right = reConstructBinaryTree(rightPre, rightMid);
return phead;
}
void printTree(TreeNode* arr[])
{
queue<TreeNode*> rel;
rel.push(arr[0]);
while (!rel.empty())
{
TreeNode* front = rel.front();
cengxu.push_back(front->val);
rel.pop();
if (front->left != nullptr)
rel.push(front->left);
if (front->right != nullptr)
rel.push(front->right);
}
for (int i = 0; i < cengxu.size()-1; i++) {
cout << cengxu[i] << " ";
}
cout << cengxu[cengxu.size() - 1] << endl;
}
void PostOrder(TreeNode* r)
{
if (r == NULL)
return;
if (r != NULL) {
PostOrder(r->left);
PostOrder(r->right);
post.push_back(r->val);
}
return;
}
int main()
{
vector<int> preVec;
vector<int> midVec;
int n, a;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a;
preVec.push_back(a);
}
for (int i = 0; i < n; i++) {
cin >> a;
midVec.push_back(a);
}
TreeNode* root = reConstructBinaryTree(preVec, midVec);
printTree(&root);
PostOrder(root);
for (int i = 0; i < post.size() - 1; i++) {
cout << post[i] << " ";
}
cout << post[post.size() - 1];
}