PTA:03-樹2 List Leaves

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

題目的意思就是從上往下、從左往右輸出所有的葉子,屬於典型的層次遍歷實現。

#include<iostream>
#include<cstdio>
#include<cmath>
#include <queue>
using namespace std;
#define MaxTree 10
#define Tree int 
#define Null -1
struct Node{
	Tree left;
	Tree right;
	Tree data;
}T1[MaxTree];
Tree BuildTree(struct Node T[]);
void FoundIndex(Tree R1,queue<Node> q);
int main()
{	
	Tree R1,R2;
	R1 = BuildTree(T1);
	queue<Node> q;
	FoundIndex(R1, q);
	return 0;
}
Tree BuildTree(struct Node T[]){
	int num;
	char cL,cR,c;
	Tree Root = Null;
	cin >> num;
	Tree check[MaxTree] = {0};
	if(num){


		for(int i = 0;i < num;i++){
			T[i].data = i;
			cin >> cL >> cR;
			if(cL != '-'){
				T[i].left = cL- '0';
				check[T[i].left] = 1;
			}else{
				T[i].left = Null;
			}
			if(cR != '-'){
				T[i].right = cR- '0';
				check[T[i].right] = 1;
			}else{
				T[i].right = Null;
			}
		}
		for(int i = 0;i < num ; i++){
			if(check[i] == 0){
				Root = i;
				break;
			}
		}
		return Root;
	}
}
void FoundIndex(Tree R1,queue<Node> q){
	q.push(T1[R1]);
	while(!q.empty()){
		Node tmp = q.front();
		q.pop();
		if(tmp.left != Null){
			q.push(T1[tmp.left]);
		}
		if(tmp.right != Null){

			q.push(T1[tmp.right]);
		}
		if(tmp.left == Null && tmp.right == Null){
			if(q.empty()){
				cout<<tmp.data;
			}else{
				cout<<tmp.data<<' ';
			}
		}
	}
	cout<<endl;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章