List Leaves (25 分)
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
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, 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 one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
题目分析:
这道题的题意是按照层序遍历的方法,输出所有的叶节点。那么解这道题分两步,首先,依据给出的信息建树。第二步就是进行层序遍历输出叶节点。建树的话就用数组建就行,然后返回数的根节点。进行层序遍历则借助堆栈,首先将根节点push进去,然后再把左右儿子加到堆栈当中,再依次循环,直到堆栈为空,如果一个节点的左右儿子都为空,说明它是叶节点,就输出。
代码如下:
#include <iostream>
#include <queue>
#define Tree int
#define Max 100
#define Null -1
using namespace std;
struct TreeNode{
Tree left;
Tree right;
}T[Max];
int BuildTree(struct TreeNode* T1); //建树
void PrintListLeaves(struct TreeNode* T1, Tree R); //输出叶节点
int main()
{
Tree T2;
T2 = BuildTree(T);
if(T2 == -1) { //当为空树的情况,直接输出0
cout << 0 << endl;
return 0;
} else
PrintListLeaves(T, T2);
return 0;
}
int BuildTree(struct TreeNode* T1)
{
int n, i, Boot = -1;
char l, r;
int check[Max] = {0};
cin >> n;
getchar();
if( n ) {
for( i=0; i<n; i++) {
scanf("%c %c", &l, &r);
getchar();
if( l != '-' ) {
T[i].left = l - '0';
check[T[i].left] = 1;
} else
T[i].left = Null;
if( r != '-' ) {
T[i].right = r - '0';
check[T[i].right] = 1;
} else
T[i].right = Null;
}
for( i=0; i<n; i++ ) {
if( !check[i] )
break;
}
Boot = i;
}
return Boot;
}
void PrintListLeaves(struct TreeNode* T1, Tree R)
{
queue<int> s; //借助队列,进行层序遍历
int symbol = 0, j;
s.push(R); //把根节点加入队列
while( !s.empty() ) {
j = s.front();
s.pop();
if( (T1[j].left==Null) && (T1[j].right==Null) ) { //输出叶节点
if(symbol == 0)
symbol = 1;
else
cout << " ";
cout << j;
}
if( T1[j].left != Null ) //当左右孩子不为空时,加入队列
s.push(T1[j].left);
if( T1[j].right != Null )
s.push(T1[j].right);
}
cout << endl;
}
上一篇: django框架自定义用户表操作示例
下一篇: 智能手环纯粹的数据记录并不会带来乐趣
推荐阅读
-
js遍历list集合方法(3分钟教你15种循环遍历)
-
js遍历list集合方法(3分钟教你15种循环遍历)
-
三星Galaxy S20 Ultra优化到位:25W充满5000mAh用时59分钟
-
1086 Tree Traversals Again (25 分)(二叉树的遍历)
-
1004 Counting Leaves (30 分)(树的遍历)
-
科学敷面膜时间是多长?敷面膜超过25分钟会发生什么
-
【PAT】B1085 PAT单位排行(25 分)(c++实现)
-
联想Z6 Pro DxOMark拍照成绩公布:95分位列第25
-
iQOO Z3发布会定档3月25日:搭载骁龙768G 跑分超45万
-
7-3 奇数阶魔阵 (25分)