列出叶结点 (25 分)

对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。

输入格式:

首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。

输出格式:

在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例:

4 1 5

解题思路

用结构体存节点信息,先记录节点序号,左孩子,右孩子。找到根节点,即不是任何节点孩子的节点,从根节点开始搜索,因为题目要求从上到下,从左到右,所以搜索的时候要记录一下深度,搜索顺序先左孩子再右孩子,并记录是第几(id)个搜到的节点,这样同样深度的节点里,在右边的会比在左边的晚搜到。把深度和id存入结构体。搜索完后排序,让深度小(高)的,深度相同且id小(左边)的,排在前面。然后遍历,没有左孩子且没有右孩子(叶子节点)的,输出其节点序号。

代码如下

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct T{
	int h, loc; //高度,第几个搜到 
	int lchild, rchild;  //左孩子,右孩子 
	int num;  //节点序号 
	bool operator<(const T& a)const{
		if(h != a.h)
			return h < a.h;
		else
			return loc < a.loc;
	}
};
T tree[15];
int id;
void dfs(int x, int cnt)
{
	id ++;
	tree[x].h = cnt;
	tree[x].loc = id;
	//cout << x << " " << tree[x].loc << endl;
	if(tree[x].lchild != -1){
		dfs(tree[x].lchild, cnt + 1);
	}
	if(tree[x].rchild != -1){
		dfs(tree[x].rchild, cnt + 1);
	}
}
int main()
{
	int n;
	cin >> n;
	bool vis[15] = {0}; //i有没有父亲节点 
	for(int i = 0; i < n; i ++){
		tree[i].num = i;
		string str1, str2;
		cin >> str1 >> str2;
		if(str1[0] != '-'){
			int num = str1[0] - '0';
			tree[i].lchild = num;
			vis[num] = true;
		}
		else
			tree[i].lchild = -1;
		if(str2[0] != '-'){
			int num = str2[0] - '0';
			tree[i].rchild = num;
			vis[num] = true;
		}
		else
			tree[i].rchild = -1;
	}
	int root = -1;
	for(int i = 0; i < n; i ++){  //找根节点 
		if(!vis[i]){  
			root = i;
			break;
		}
	}
	id = 0;
	dfs(root, 1);
	sort(tree, tree + n); //排序 
	bool first = true;
	for(int i = 0; i < n; i ++){
		if(tree[i].lchild == -1 && tree[i].rchild == -1){
			if(first)
				first = false;
			else
				cout << " ";
			cout << tree[i].num;	
		}
	}
	cout << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/whisperlzw/article/details/88297112