您的位置:首页 > 其它

1102 Invert a Binary Tree (25 分)——甲级:建树输出中序、层序(二叉树镜像输出)

2019-08-13 15:02 411 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/destiny_balabala/article/details/99436180

The following is from Max Howell @twitter:

Now it’s your turn to prove that YOU CAN invert a binary tree!

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

题目大意:结点编号从0到n-1。对于每个结点,给出左右儿子存在情况以及索引,要求输出层序和中序的镜像。
思路:用结构体数组存二叉树,check数组标记有父亲节点的结点,最后没有被标记的就是根节点。利用根节点输出即可。

代码如下:

#include <iostream>
#include <queue>
using namespace std;
struct node
{
int left;
int right;//-1表示没有对应儿子结点
}a[10];
int n, check[10], cnt;
int build(int n)
{
int i;
for(i = 0; i < n; i++)
{
char lchild, rchild;
cin >> lchild >> rchild;
if(lchild == '-') a[i].left = -1;
else
{
a[i].left = lchild-'0';
check[lchild-'0'] = 1;
}
if(rchild == '-') a[i].right = -1;
else
{
a[i].right = rchild-'0';
check[rchild-'0'] = 1;
}
}
for(i = 0; i < n; i++) if(!check[i]) return i;//没有被标记的即为根节点
}
void level_order(int t)
{
queue<int>q;
int flag = 0;
q.push(t);
while(!q.empty())
{
int x = q.front();
if(!flag)
{
flag = 1;
cout << x;
}
else cout << " " << x;
if(a[x].right != -1) q.push(a[x].right);
if(a[x].left != -1) q.push(a[x].left);//镜像:先右,后左
q.pop();
}
cout << endl;
}
void in_order(int t)
{
if(t == -1) return ;
in_order(a[t].right);
cnt++;
if(cnt == n) cout << t << endl;
else cout << t << " ";
in_order(a[t].left);//镜像:右-根-左
}
int main()
{
cin >> n;
int head = build(n);
level_order(head);
in_order(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: