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
用了二叉树的数组表示,即子节点下标除以2向下取整的结果就是父节点的下标,唯一需要注意的是在最坏情况下10个节点组成的二叉树扩展出的完美二叉树的节点有1023个,注意数组大小不要越界就好。
本题让我深深地认识到用数组表示二叉树确实空间浪费巨大,还好最多只有十个节点,如果是100个节点...那还是老老实实地去构造树再用层次遍历吧...
#include <stdio.h> #include <stdlib.h> int main() { int n; scanf("%d", &n); getchar(); char nodelist[10][2]; int countlist[10] = {0}; int leaf = 0, maxnode = 1; int i; for(i = 0; i < n; i++) { scanf("%c %c", &nodelist[i][0], &nodelist[i][1]); getchar(); if(nodelist[i][0] >= '0' && nodelist[i][0] <= '9') countlist[nodelist[i][0]-'0'] ++; if(nodelist[i][1] >= '0' && nodelist[i][1] <= '9') countlist[nodelist[i][1]-'0'] ++; else if(nodelist[i][1] == '-' && nodelist[i][0] == '-') leaf ++; maxnode *= 2; } for(i = 0; i < n; i++) //找根节点 if(countlist[i] == 0) break; int *node = (int *) malloc (maxnode * sizeof(int)); node[1] = i; for(i = 2; i <= maxnode-1; i++) node[i] = -1; for(i = 1; i <= maxnode-1; i++) { if(node[i] != -1) { if(nodelist[node[i]][0] >= '0' && nodelist[node[i]][0] <= '9') node[2*i] = nodelist[node[i]][0] - '0'; if(nodelist[node[i]][1] >= '0' && nodelist[node[i]][1] <= '9') node[2*i+1] = nodelist[node[i]][1] - '0'; } } for(i = 1; i <= maxnode-1; i++) { if(node[i] != -1 && nodelist[node[i]][0] == '-' && nodelist[node[i]][1] == '-') { printf("%d", node[i]); if(--leaf > 0) printf(" "); } } printf("\n"); return 0; }