03-树2 List Leaves (25分)
来源:互联网 发布:win7 优化 编辑:程序博客网 时间:2024/05/12 08:12
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:
81 -- -0 -2 7- -- -5 -4 6
Sample Output:
4 1 5
借鉴别人的代码,真是妙啊
#include<stdio.h>#include<ctype.h>struct node{int root;int left;int right;};int main(){int n,i;scanf("%d\n",&n);struct node tree[n];for(i=0;i<n;i++){tree[i].root=1;tree[i].left=-1;tree[i].right=-1;}char cl,cr;for(i=0;i<n;i++){scanf("%c %c",&cl,&cr);if(isdigit(cl)){tree[i].left=cl-'0';tree[cl-'0'].root=-1;}if(isdigit(cr)){tree[i].right=cr-'0';tree[cr-'0'].root=-1;}getchar();}int root;for(i=0;i<n;i++){if(tree[i].root==1){root=i;break;}}int queue[n];int head=0,rear=0;int flag=0;queue[rear++]=root;while(rear-head){int node=queue[head++];if(tree[node].left!=-1){queue[rear++]=tree[node].left;}if(tree[node].right!=-1){queue[rear++]=tree[node].right;}if(tree[node].left==-1&&tree[node].right==-1){if(flag==0){printf("%d",node);flag=1;}else{printf(" %d",node);}}}}
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- PAT - 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分) (查找叶子节点)
- [pta]03-树2 List Leaves (25分)
- js对象的深拷贝和浅拷贝
- 程序1--互不重复的三位数
- 阻止a标签默认行为的几种简单方法
- Spring 实现数据库读写分离
- 对你来说,哪一个深度学习网络是最佳选择?(2)
- 03-树2 List Leaves (25分)
- 性能测试并发数的计算
- AES加密解密算法
- 随意组合
- 123123
- VS2010 CUDA和C++混合编译
- Makefile笔记(1)
- 阻塞与非阻塞设置
- JAVA中数据库操作中sql语句遇到的问题