歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 樹2. List Leaves (25)

樹2. List Leaves (25)

日期:2017/3/1 9:25:34   编辑:Linux編程

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

題目大意: 通過輸入節點數以及每個節點的左兒子和右兒子,從上到下打印出葉節點。
題目關鍵:要理解輸入的第幾行就是代表該節點的值為幾。例如樣例輸入中第0行的1 -代表值為0的節點左孩子的值為1,即指向第1行,右孩子為空(-1)
樹模型如下:



代碼如下:

#include <cstdio>
#include <cctype>

#define N 10

typedef struct Node
{
int data, left, right;
} TreeNode;
TreeNode node[N];
TreeNode Queue[N]; //數組實現隊列

int first = -1, last = -1;

void Push(TreeNode tn);
TreeNode Pop();
void printLeaves(int root, int n);

int charToInt(char ch);

int main()
{
int n;
bool isRoot[N];
int root;

scanf("%d\n", &n);
for (int i = 0; i < n; i++)
isRoot[i] = 1;
for (int i = 0; i < n; i++)
{
char cLeft, cRight;
scanf("%c %c", &cLeft, &cRight);
getchar(); //讀取緩存區的回車符
node[i].left = charToInt(cLeft);
node[i].right = charToInt(cRight);
node[i].data = i;
//一個節點的左孩子和右孩子一定不是根節點
if (node[i].left != -1)
isRoot[node[i].left] = 0;
if (node[i].right != -1)
isRoot[node[i].right] = 0;
}
//找到根節點
for (int i = 0; i < n; i++)
{
if (isRoot[i])
{
root = i;
break;
}
}
printLeaves(root, n);

return 0;
}

void Push(TreeNode treeNode)
{
Queue[++last] = treeNode;
}

TreeNode Pop()
{
return Queue[++first];
}

//層序遍歷樹節點並打印出葉節點:隊列實現
void printLeaves(int root, int n)
{
int leaves[N];
int k = 0;
Push(node[root]);
for (int i = 0; i < n; i++)
{
TreeNode tn = Pop();
//左孩子和右孩子都不存在時,將葉節點的值保存到數組中,便於格式化打印
if (tn.left == -1 && tn.right == -1)
leaves[k++] = tn.data;
if (tn.left != -1)
Push(node[tn.left]);
if (tn.right != -1)
Push(node[tn.right]);
}
for (int i = 0; i < k-1; i++)
printf("%d ", leaves[i]);
printf("%d\n", leaves[k-1]);
}

int charToInt(char ch)
{
if (isdigit(ch))
return ch - '0';
else
return -1;
}

Copyright © Linux教程網 All Rights Reserved