03-树2. List Leaves (25)
题目来源:http://www.patest.cn/contests/mooc-ds/03-%E6%A0%912
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 6Sample Output:
4 1 5
题目大意: 通过输入节点数以及每个节点的左儿子和右儿子,从上到下打印出叶节点。
题目关键:要理解输入的第几行就是代表该节点的值为几。例如样例输入中第0行的1 -代表值为0的节点左孩子的值为1,即指向第1行,右孩子为空(-1)
树模型如下:
![](https://i-blog.csdnimg.cn/blog_migrate/f949f953147ae97d747664d658484ecb.png)
代码如下:
1 #include <cstdio> 2 #include <cctype> 3 4 #define N 10 5 6 typedef struct Node 7 { 8 int data, left, right; 9 } TreeNode; 10 TreeNode node[N]; 11 TreeNode Queue[N]; //数组实现队列 12 13 int first = -1, last = -1; 14 15 void Push(TreeNode tn); 16 TreeNode Pop(); 17 void printLeaves(int root, int n); 18 19 int charToInt(char ch); 20 21 int main() 22 { 23 int n; 24 bool isRoot[N]; 25 int root; 26 27 scanf("%d\n", &n); 28 for (int i = 0; i < n; i++) 29 isRoot[i] = 1; 30 for (int i = 0; i < n; i++) 31 { 32 char cLeft, cRight; 33 scanf("%c %c", &cLeft, &cRight); 34 getchar(); //读取缓存区的回车符 35 node[i].left = charToInt(cLeft); 36 node[i].right = charToInt(cRight); 37 node[i].data = i; 38 //一个节点的左孩子和右孩子一定不是根节点 39 if (node[i].left != -1) 40 isRoot[node[i].left] = 0; 41 if (node[i].right != -1) 42 isRoot[node[i].right] = 0; 43 } 44 //找到根节点 45 for (int i = 0; i < n; i++) 46 { 47 if (isRoot[i]) 48 { 49 root = i; 50 break; 51 } 52 } 53 printLeaves(root, n); 54 55 return 0; 56 } 57 58 void Push(TreeNode treeNode) 59 { 60 Queue[++last] = treeNode; 61 } 62 63 TreeNode Pop() 64 { 65 return Queue[++first]; 66 } 67 68 //层序遍历树节点并打印出叶节点:队列实现 69 void printLeaves(int root, int n) 70 { 71 int leaves[N]; 72 int k = 0; 73 Push(node[root]); 74 for (int i = 0; i < n; i++) 75 { 76 TreeNode tn = Pop(); 77 //左孩子和右孩子都不存在时,将叶节点的值保存到数组中,便于格式化打印 78 if (tn.left == -1 && tn.right == -1) 79 leaves[k++] = tn.data; 80 if (tn.left != -1) 81 Push(node[tn.left]); 82 if (tn.right != -1) 83 Push(node[tn.right]); 84 } 85 for (int i = 0; i < k-1; i++) 86 printf("%d ", leaves[i]); 87 printf("%d\n", leaves[k-1]); 88 } 89 90 int charToInt(char ch) 91 { 92 if (isdigit(ch)) 93 return ch - '0'; 94 else 95 return -1; 96 }