03-树1. List Leaves (25)
2015-05-05 12:52
441 查看
03-树1. List Leaves (25)
时间限制400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
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
#include<stdio.h> #include<stdlib.h> #define MaxSize 20 int input(void){ char c; do{ c = getchar(); }while(c != '-' && (c<'0' || c>'9')); if(c == '-') return -1; else return c-'0'; } struct node { int left; int right; }; int main(){ void InOutQueue(int* p,struct node* tree,int* star,int* end); int num,i,head,j[20]; int point=0; for(i=0;i<10;i++){j[i]=-1;} char temp; // struct node *tree; scanf("%d",&num); // tree=(struct node *)malloc(num*sizeof(struct node)); struct node tree[15]; for(i=0;i<num;i++){ tree[i].left= input(); if(tree[i].left!=-1) j[tree[i].left]=1; tree[i].right= input(); if(tree[i].right!=-1) j[tree[i].right]=1; } //j[tree[i].right]=-1; for(i=0;i<num;i++){ if(j[i]==-1){ head=i; break; } } int queue[num+1],star = -1,end = 0; queue[0] = -1; queue[num] = -1; queue[end] = head; end++; while(1!= end -star){ InOutQueue(queue,tree,&star,&end); } } void InOutQueue(int* p,struct node* tree,int* star,int* end){ int t = p[(*star)+1]; static int P = 0; if(tree[t].left!=-1){ p[*end] = tree[t].left; (*end)++; } if(tree[t].right!=-1){ p[*end] = tree[t].right; (*end)++; } if(tree[t].left == -1 && tree[t].right == -1){ if(!P){ printf("%d",t); P = 1; }else printf( 4000 " %d",t); } (*star)++; }
相关文章推荐
- 03-树1. List Leaves (25)
- PAT : 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- 【解题报告】【浙大PAT】03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- PAT03-树1. List Leaves (25)
- PAT 03-树1. List Leaves (25)(C)
- 03-树2. List Leaves (25)
- PAT 数据结构 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) Java
- 03-树2. List Leaves (25) Python C
- PAT 03-2. List Leaves (25)
- 03-2. List Leaves (25)
- PAT 03-2. List Leaves (25)
- 03-树2. List Leaves(25)