题目
03-树2 List Leaves (25 分)
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
我的答案
//
// Created by allenhsu on 2018/10/30.
// 本质上是二叉树的层序遍历方法,之前讲过的是用队列实现
//
#include <iostream>
#include <queue>
using namespace std;
#define Null -1
#define MaxElement 10
typedef int Tree;
typedef int Element;
struct TreeNode {
Element value;
Tree Left;
Tree Right;
};
struct TreeNode T1[MaxElement];
int N = 0;
// 构建树并返回根节点
Tree BuildTree(struct TreeNode T[]) {
cin >> N;
char left, right;
int check[MaxElement], root = Null;
for (int j = 0; j < N; ++j) {
check[j] = 0;
}
for (int i = 0; i < N; ++i) {
T[i].value = i;
cin >> left >> right;
if (left != '-') {
T[i].Left = left - '0';
check[T[i].Left] = 1;
} else
T[i].Left = Null;
if (right != '-') {
T[i].Right = right - '0';
check[T[i].Right] = 1;
} else
T[i].Right = Null;
}
for (int k = 0; k < N; ++k) {
if (check[k] == 0) {
root = k;
}
}
return root;
}
void findLeaves(Tree tree){
if (tree == Null) return;
queue<int> q;
q.push(tree);
int temp, flag = 1;
while (!q.empty()){
temp = q.front();
q.pop();
if (T1[temp].Left == Null && T1[temp].Right == Null){
if (flag){
cout << temp;
flag = 0;
} else{
cout << " "<< temp;
}
}
if (T1[temp].Left != Null)
q.push(T1[temp].Left);
if (T1[temp].Right != Null)
q.push(T1[temp].Right);
}
}
int main() {
Tree tree;
tree = BuildTree(T1);
findLeaves(tree);
return 0;
}
问题解剖
- 该题目与上一道树的同构大部分一致,关键处在查找叶子节点的遍历树的方法上。使用的是队列实现层次遍历,思想是:push一个节点,随后pop出来,把pop的节点的左右子节点再push进去,知道队列为空。
- 最开始越想越复杂,其实构建int类型的queue就可以,更简便,更实用!