PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1758字,纯文字阅读大概需要3分钟。
内容图文
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 (≤30), 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
Process
我树方面的题好菜啊…这两天去搭自己的博客网站了所以更新少,网站搭到一半不想搭了,完全是不会前端…毕竟也没学过不是…
Code
#include<bits/stdc++.h>
using namespace std;
#define MAX 10010
int n, cnt;
int post[MAX], inorder[MAX], ans[MAX];
void tree(int start, int end, int root, int index)
{
if (start > end)
return;
int k = end;
ans[index] = post[root];
for (int i = start; i < end; i++)
if (inorder[i] == post[root])
{
k = i;
break;
}
tree(start, k - 1, root - (end - k + 1), index * 2 + 1);
tree(k + 1, end, root - 1, index * 2 + 2);
}
int main()
{
memset(ans, -1, sizeof(ans));
cin >> n;
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++)
cin >> inorder[i];
tree(0, n - 1, n - 1, 0);
for (int i = 0; i < MAX; i++)
{
if (ans[i] != -1)
cout << ans[i] << (++cnt == n ? "\n" : " ");
if (cnt == n)
break;
}
return 0;
}
ccql
发布了253 篇原创文章 · 获赞 31 · 访问量 1万+
私信
关注
内容总结
以上是互联网集市为您收集整理的PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历)全部内容,希望文章能够帮你解决PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。