Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2

已知后序遍历和中序遍历输出层序遍历
 #include <iostream>
#include <queue>
using namespace std;
int *pos, *ord;//存放后序和中序遍历数据
struct Node
{
int val;
Node *l, *r;
Node(int a = ) :val(a), l(nullptr), r(nullptr) {}
};
Node* createTree(int posL,int posR, int ordL, int ordR)
{
if (posL > posR)
return nullptr;
Node *root = new Node();
root->val = pos[posR];//根节点值
int k;
for (k = ordL; k <= ordR; ++k)
{
if (ord[k] == pos[posR])//找到原树的根
break;
}
int numL = k - ordL;//左子树节点数量
//递归构造左子树
root->l = createTree(posL, posL + numL - , ordL, k - );
//递归构造右子树
root->r = createTree(posL + numL, posR - , k + , ordR);//取出根节点
return root;
}
void getResBFS(Node* root)
{
queue<Node*>q;
Node* p = nullptr;
q.push(root);
cout << root->val;
while (!q.empty())
{
p = q.front();
if (p != root)
cout << " " << p->val;
q.pop();
if (p->l != nullptr)
q.push(p->l);
if (p->r != nullptr)
q.push(p->r);
}
cout << endl;
} int main()
{
int N;
cin >> N;
pos = new int[N];
ord = new int[N];
for (int i = ; i < N; ++i)
cin >> pos[i];
for (int i = ; i < N; ++i)
cin >> ord[i];
Node* root = createTree(, N - , , N - );
getResBFS(root);
return ;
}

最新文章

  1. 配置 linux-bridge mechanism driver - 每天5分钟玩转 OpenStack(77)
  2. 文本切割软件Replace Pioneer
  3. EF并非我们想象的那么智能
  4. 将图片的二进制字节 在HTML页面中显示
  5. PyCharm4注册码--软件安装
  6. Ansible用于网络设备管理 part 0 安装和登录网络设备
  7. JavaScript原型链和instanceof运算符的暧昧关系
  8. asp.net runat=&quot;server&quot; &amp;&amp; hiddenfield
  9. 【8】了解Bootstrap栅格系统基础案例(3)
  10. 《A First Course in Probability》-chaper7-期望的性质-期望的性质-协方差
  11. 作为java应届生,面试求职那点事
  12. JS拖动浮动DIV
  13. Autofac 组件、服务、自动装配(2)
  14. activiti怎么实现用户自定义流程?请先看这里
  15. Flask 学习 十一 关注者
  16. oracle增加记录谁在连接你的数据库
  17. redis 模糊删除key
  18. c strlen和sizeof详解
  19. hdu 2845 Beans(最大不连续子序列和)
  20. 【git】git使用

热门文章

  1. mysql中geometry类型的简单使用
  2. Activity详解三 启动activity并返回结果 转载 https://www.cnblogs.com/androidWuYou/p/5886991.html
  3. 区间dp及优化
  4. 06_mybatis关系映射
  5. USACO 2008 November Gold Cheering up the Cows /// MST oj24381
  6. 机器学习-一对多(多分类)代码实现(matlab)
  7. java笔试之自守数
  8. 编写Map处理逻辑
  9. unity3d入门 Demo 学习记录
  10. JS数组 编程练习 使用Javascript语言,把以下数组 在页面显示如下图所示的图案