二叉树的层序遍历(c++)

题目

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

输入格式
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.
先输入一个小于10的正整数N,代表结点的总数,在接下来的N行每行输入一个结点信息。输入的信息代表了左右儿子结点,当输入’-'时代表无左/右儿子结点,输入的左右儿子结点的信息之间用空格隔开。

输出格式
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.
输出的信息为每个测试用例的叶节点,输出顺序为由上至下,由左至右,在每个结点之间用空格隔开,最后一个结点后面没有多余空格。
输入样例

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例

4 1 5

这道题算是二叉树中比较基本的题目,主要考察的是二叉树的构建以及对于二叉树的层次遍历。二叉树的层次遍历一般采用的是使用队列来进行遍历。一开始队列中只有一个根节点,当队列的第一个结点出队时,该节点对应的左右儿子结点入队,依次遍历直至整个队列中无结点。当出队的结点为叶结点时,打印出来,最后打印出所有的叶节点。这种遍历方式可以确保题目中提出的从上至下、从左至右打印叶节点的要求。

代码如下:

#define null -1//无左/右儿子结点时序号为null

#include<iostream>
using namespace std;
struct TreeNode//本题采用静态链表的方法构建二叉树,每结点结构有三个信息,分别为结点序号
{
                 //以及左右儿子结点的序号
	int Data;
	int  Left;
	int Right;
}T[10];//用T来存储整个二叉树

struct queue//队列的链式存储
{
   
	TreeNode tree;
	queue* next;
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值