列出叶结点 pta简单易懂

本文介绍了一种算法,用于从上到下、从左到右的顺序输出给定二叉树的所有叶节点。通过使用层序遍历的方法,并利用队列来处理,实现了对二叉树叶节点的有效遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。

输入格式:

首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。

输出格式:

在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

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

输出样例:

4 1 5

本题只要找出根节点,然后从根节点按照层序遍历写即可。其中读入用scanf返回值得特性能简单处理,层序用队列处理比较方便。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<vector>
#define inf 2147483647
#define rep(i,a,b) for(int i=a;i<b;i++)
#define  rr read()
#define ll long long
#define repb(i,a,b) for(int i=a;i<=b;i++)
#define CloseIo   ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
int read()
{
    char ch = getchar();
	int x = 0, f = 1;
    while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
    while('0' <= ch && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
    return x * f;
}
struct node
{
	 int lchild,rchild;
	 node()
	 {
	 	lchild=-1;
	 	rchild=-1;
	 }
}z[100];
void ceng(int s)
{
	 queue<int>q;
	 q.push(s);
	 int flag=0;
	 while(!q.empty())
	 {
	 	 int i=q.front();
	 	 q.pop();
	 	 if(z[i].lchild!=-1)q.push(z[i].lchild);
	 	 if(z[i].rchild!=-1)q.push(z[i].rchild);
	 	 if(z[i].lchild==-1&&z[i].rchild==-1)
	 	 {
	 	 	flag++;
	 	 	if(flag!=1)printf(" ");
	 	 	printf("%d",i);
		  }
	 }
}
int main()
{
   int n=rr;
   int f[105]={0};
   rep(i,0,n)
   {  
      rep(j,0,2)
     {
   	    int t;
   	   if(scanf("%d",&t)==1)
   	   { 
		  if(j==0)
		  z[i].lchild=t;
	      else
		  z[i].rchild=t;
		   f[t]++;
		}
   	  
      }
   
   }

   rep(i,0,n)
   {
   	 if(!f[i])
   	 {
   	 	cent(i);
   	 	break;
		}
   }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值