Given a tree, you is supposed to list all the leaves in the order of the top down, and left to right.
Input Specification:
Each input file contains the one test case. For each case, the first line gives a positive integerN≤10) which is the total number of nodes in the tree--and hence the nodes was numbered from 0 toN−1. Then N lines follow, each corresponds to a node, and gives the indices of the "the" and right children of the node. If the child does not exist, a "-" 'll be put on the position. Any pair of children is separated by a space.
Output Specification:
For each test case, print in one line all the leaves ' indices in the order of the top down, and left to right. There must is 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
Analysis: The amount of data is very small, how to write all over AH. So I used a struct array to simulate a tree-like structure. Each leaf node is then found, but the output is required. First, the output depth of the node, the same depth of the leaf node
First, the left leaf node is output, and then the leaf node on the right is output.
The look of the example after the achievement
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include < Queue> #include <algorithm>using namespace std;struct node{int ll; int RR; int data; int dep; int DFN;} q[20];struct n{int num; int dep; int DFN; BOOL operator< (const N &DD) const{if (DEP==DD.DEP) return dd.dfn<dfn; else return dd.dep<dep; }};int cnt;void dfs_leaf (int root, int deep) {if (q[root].ll==-1 && q[root].rr==-1) return; if (q[root].ll!=-1) {int v=q[root].ll; q[v].dep=deep+1; q[v].dfn=cnt++; Dfs_leaf (V, deep+1); } if (q[root].rr!=-1) {int v=q[root].rr; q[v].dep=deep+1; q[v].dfn=cnt++; Dfs_leaf (V, deep+1); }}int Main () {int n; scanf ("%d%*c", &n); int I, j, K; Char a[5], b[5]; for (i=0; i<n; i++) {scanf ("%s%s", A, b); if (a[0]== '-') {q[i].ll=-1; }else{ q[i].ll=a[0]-48; } if (b[0]== '-') {q[i].rr=-1; }else{q[i].rr=b[0]-48; }//simulation of each tree node}//achievement complete bool f[20];//mark each node is not a son memset (F, false, sizeof (f)); for (i=0; i<n; i++) {if (q[i].ll!=-1) {f[q[i].ll]=true; } if (q[i].rr!=-1) {f[q[i].rr]=true; }} int root; for (i=0; i<n; i++) {if (f[i]==false) {root=i; }}//printf ("root =%d\n", root); Cnt=1; q[root].dfn=0; Q[root].dep=0; Dfs_leaf (root, 0); priority_queue<n>que; N cur; for (i=0; i<n; i++) {if (q[i].ll==-1&&q[i].rr==-1) {cur.num=i; CUR.DEP=Q[I].DEP; CUR.DFN=Q[I].DFN; Que.push (cur); printf ("%d nodes: depth%d order%d\n", I, Q[I].DEP, Q[I].DFN); }} bool Z=false; while (!que.empty ()) {if (z==false) {printf ("%d", que.top (). num); z=true; Que.pop (); } else{printf ("%d", que.top (). num); Que.pop (); }}printf ("\ n"); return 0;}
The tree List Leaves "uses arrays to simulate tree-like construction and search for leaf nodes + to output each leaf node according to special rules"