已知二叉树的前序和中序,请输出层序
输入格式:
第一个数N,代表二叉树具有N个节点(N<50)
接着一行是N个整数,整数保证互不相同,整数之间有两个空格,表示前序
接着一行也是N个整数,整数之间有两个空格,表示中序
输出格式:
N个整数,整数之间有两个空格,表示层序
输入样例:
10
7 10 2 5 1 3 8 4 6 9
10 2 7 3 1 5 8 6 4 9
输出样例:
7 10 5 2 1 8 3 4 6 9
//先通过先序和中序建立二叉树,再层序遍历
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
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; //定义一个队列,数据类型是二叉树指针,不要仅是int!!不然无法遍历
rel.push(arr[0]);
while (!rel.empty())
{
TreeNode* front = rel.front();
cout<<front->val<<" ";
rel.pop(); //删除最前面的节点
if (front->left != nullptr) //判断最前面的左节点是否为空,不是则放入队列
rel.push(front->left);
if (front->right != nullptr)//判断最前面的右节点是否为空,不是则放入队列
rel.push(front->right);
}
}
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);
}