编程题07 List Leaves

该博客介绍了如何使用C++构建一棵二叉树,并通过队列实现层次遍历。主要内容包括读取输入构建二叉树节点,计算没有子节点的叶子节点数量,以及层次遍历并打印这些叶子节点。

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

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

#define MaxTree 10
#define Null -1
typedef int ElementType;
typedef int Tree;
struct TNode {
	ElementType Data;
	Tree Left;
	Tree Right;
}T[MaxTree];
int sum = 0;

Tree BuildTree(struct TNode T[]);
void PrintTree(Tree R);

int main() {
	Tree R;
	R = BuildTree(T);
	PrintTree(R);
	return 0;
}

Tree BuildTree(struct TNode T[]) {
	int N;
	cin >> N;
	Tree Root = Null;
	if (N) {
		int i;
		char cl, cr;
		int* check = new int[N];
		for (i = 0; i < N; i++) check[i] = 0;
		for (i = 0; i < N; i++) {
			cin >> cl >> cr;
			T[i].Data = i;
			if ((cl == '-') && (cr == '-')) sum++;

			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 (i = 0; i < N; i++)
			if (!check[i]) break;
		Root = i;
	}
	return Root;
}

void PrintTree(Tree R) {
	if (R == Null) return;

	queue<Tree>Q;
	Q.push(R);
	while (!Q.empty()) {
		R = Q.front();
		Q.pop();
		if (T[R].Left == Null && T[R].Right == Null) {
			cout << R;
			sum--;
			if (sum) cout << " ";
		}
		if (T[R].Left != Null) Q.push(T[R].Left);
		if (T[R].Right != Null) Q.push(T[R].Right);
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值