03-树2 List Leaves(C++)

cpp 复制代码
# include <iostream>
# include <cstdio>

struct Node {
	int left;
	int right;
};
struct Tree {
	int n;
	int root;
	Node * treeList;

	Tree(int _n) :n(_n)
	{
		bool isRoot[15];
		for (int i = 0; i < n; ++i) isRoot[i] = true;

		treeList = new Node[n];
		for (int i = 0; i < n; ++i)
		{
			char b, c;
			scanf("\n%c %c", &b, &c);

			if (b == '-') 
				treeList[i].left = -1;
			else 
				treeList[i].left = b - '0', isRoot[treeList[i].left] = false;


			if (c == '-') 
				treeList[i].right = -1;
			else 
				treeList[i].right = c - '0', isRoot[treeList[i].right] = false;
		}

		root = n;
		while (--root >= 0 && !isRoot[root]);
	}

	void ListLeaves()
	{
		int queue[100], front = 0, rare = 0;
		queue[++rare] = root;
		int isFirst = true;
		while (front != rare)
		{
			int deq = queue[++front];
			if (treeList[deq].left != -1) queue[++rare] = treeList[deq].left;
			if (treeList[deq].right != -1) queue[++rare] = treeList[deq].right;
			if (treeList[deq].left == -1 && treeList[deq].right == -1)
			{
				printf("%s%d", isFirst ? "" : " ", deq); isFirst = false;
			}
		}
	}
};


int main(void)
{
	int n;
	scanf("%d", &n);
	Tree t(n);

	t.ListLeaves();
	return 0;
}
相关推荐
aichitang20245 分钟前
矩阵详解:从基础概念到实际应用
线性代数·算法·矩阵
small_wh1te_coder25 分钟前
c语言超详细知识点总结 1500行手写源码 持续更新中ing 从25年5月到6月5日
c++·c
OpenCSG1 小时前
电子行业AI赋能软件开发经典案例——某金融软件公司
人工智能·算法·金融·开源
dfsj660112 小时前
LLMs 系列科普文(14)
人工智能·深度学习·算法
SteveDraw2 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
薛定谔的算法2 小时前
《盗梦空间》与JavaScript中的递归
算法
十五年专注C++开发2 小时前
设计模式之单例模式(二): 心得体会
开发语言·c++·单例模式·设计模式
kaiaaaa3 小时前
算法训练第十一天
数据结构·算法
?!7143 小时前
算法打卡第18天
c++·算法
springfe01013 小时前
构建大顶堆
前端·算法