03-树2 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 (≤) 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
#include<cstdio> #include<queue> using namespace std; const int maxn = 15; struct Node{ int lchild,rchild; }node[maxn]; int num = 0; bool isRoot[maxn]; int change(char c){ if(c == '-') return -1; else{ isRoot[c-'0'] = false; return c-'0'; } } void print(int v){ if(num == 0){ printf("%d",v); num++; }else{ printf(" %d",v); } } void BFS(int root){ int front = -1,rear = -1; int q[maxn]; q[++front] = root; while(front!= rear){ int now = q[++rear]; if(node[now].lchild == -1 && node[now].rchild == -1) print(now); if(node[now].lchild != -1) q[++front] = node[now].lchild; if(node[now].rchild != -1) q[++front] = node[now].rchild; } // queue<int> q; // q.push(root); // while(!q.empty()){ // int now = q.front(); // q.pop(); // if(node[now].lchild==-1&&node[now].rchild==-1) // print(now); // if(node[now].lchild != -1) // q.push(node[now].lchild); // if(node[now].rchild != -1) // q.push(node[now].rchild); // } } int main(){ int n; scanf("%d",&n); for(int i = 0; i < n; i++){ isRoot[i] = true; } for(int i = 0; i < n; i++){ char a,b; getchar(); scanf("%c %c",&a,&b); node[i].lchild = change(a); node[i].rchild = change(b); } int root; for(int i = 0; i < n; i++){ if(isRoot[i] == true){ root = i; break; } } BFS(root); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)