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
附上这道题的中文链接,好多题再做都不会做了感觉

【树的应用】——列出叶结点 (25分)(附测试点)

#include <iostream> 
#include <queue>
using namespace std;

typedef struct{
    
    
	int data;
	int left,right;
}Node; 

Node node[10];
bool flag[10] = {
    
    false};

void leaves(Node x){
    
    
	queue<Node> q;
	q.push(x);
	int len = 0;
	while(!q.empty()){
    
    
		Node no = q.front();
		if(no.left==-1&&no.right==-1){
    
    
			len++;
			if(len==1)
				cout << no.data;
			else
				cout << " " << no.data;
		}
		q.pop();
		if(no.left!=-1){
    
    
			q.push(node[no.left]);
		}
		if(no.right!=-1){
    
    
			q.push(node[no.right]);
		}
	}
}

int main(){
    
    
	ios::sync_with_stdio(false);
	int n;
	char l,r;
	cin >> n;
	for(int i = 0;i<n;i++){
    
    
		cin >> l >> r;
		node[i].data = i;
		if(l!='-'){
    
    
			node[i].left = l-'0';
			flag[l-'0'] = true;
		}else{
    
    
			node[i].left = -1;
		}
		if(r!='-'){
    
    
			node[i].right = r-'0';
			flag[r-'0'] = true;
		}else{
    
    
			node[i].right = -1;
		}
	}
	int root;
	for(int i = 0;i<n;i++){
    
    
		if(!flag[i]){
    
    
			root = i;
			break;
		}
	}
	leaves(node[root]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45845039/article/details/108655522
今日推荐