中国大学MOOC-陈越、何钦铭-数据结构-2020春 PTA 03-树2 List Leaves (25分)

本文介绍了一种遍历树结构中所有叶子节点的方法,通过将原始二叉树转换为完全二叉树,利用完全二叉树的特性,即每个节点的左子树为其两倍索引,右子树为其两倍索引加一,以此来判断哪些节点是叶子节点。文章详细解释了算法的实现过程,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

在这里插入图片描述

Sample Output:

4 1 5
叶子结点查找输出思路:将原有的二叉树转换成为一个新的完全二叉树,并在新二叉树中保存原二叉树的结点位置。利用完全二叉树的特点,即第i个结点,其左子树为2i,右子树为2i+1,进行判断是否为叶子结点。
代码:

#include <stdio.h>
#define maxsize 100	
#define Tree int
			
struct TreeNode {
	int left;
	int right;
}T[maxsize];

void LevelOrder (struct TreeNode T[], int R, int N);
int BuildTree (struct TreeNode T[], int N);

int main () {
	int R, N;
	scanf ("%d", &N);
	getchar(); 
	R = BuildTree(T, N); //建立树并返回根节点位置
	LevelOrder (T, R, N) ;
	return 0;
}
int BuildTree (struct TreeNode T[], int N) {//读取输入的数据
	int i, root = -1;
	char cl, cr;
	int check [maxsize];
	if (N) {
		for (i = 0; i < N; i++) {
			check[i] = 0;
		}
		for (i = 0; i < N; i++) {
			scanf ("%c %c", &cl, &cr);
			getchar();
			if (cl != '-') {
				T[i].left = cl - '0';
				check[T[i].left] = 1;
			}
			else T[i].left = -1;
			if (cr != '-') {
				T[i].right = cr - '0';
				check[T[i].right] = 1;
			}
			else T[i].right = -1;
		}
		for (i = 0; i < N; i++) {
			if(!check[i]) break;
		}
		root = i;
	}
	return root;
}

void LevelOrder (struct TreeNode T[], int R, int N) {//查找叶子结点
	int i, j;
	int idx = 0; //用于判断当前打印的是否为第一个结点
	if (R != -1) {
		int Q[maxsize];
		for (i = 0; i < maxsize; i++) {//利用Q来保存新的树,-1代表该结点为空
			Q[i] = -1;	
		}
		Q[1] = R;//将根结点存入数组当中,从1开始
		for (i = 1, j = 0; j < N; i++) {//i为当前查找的结点编号,j为有数据的结点个数
			if (Q[i] != -1) { //当前结点不空时,在该结点对应的左右子树位置放入原树的结点编号
				Q[2*i] = T[Q[i]].left;
				Q[2*i+1] = T[Q[i]].right;
				if (Q[2*i] == -1 && Q[2*i+1] == -1) { //当前第i个结点的左右均为空时,说明为叶子结点,输出
					if (idx) printf(" ");
					idx = 1;
					printf ("%d", Q[i]);
				}
				j++;//每查找到一个有数据的结点,结点数+1
			} 
		}
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值