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;
}
相关推荐
PPPPPaPeR.6 小时前
光学算法实战:深度解析镜片厚度对前后表面折射/反射的影响(纯Python实现)
开发语言·python·数码相机·算法
看我干嘛!6 小时前
python第五次作业
算法
历程里程碑6 小时前
Linux 库
java·linux·运维·服务器·数据结构·c++·算法
Sheep Shaun6 小时前
如何让一个进程诞生、工作、终止并等待回收?——探索Linux进程控制与Shell的诞生
linux·服务器·数据结构·c++·算法·shell·进程控制
Pluchon6 小时前
硅基计划4.0 简单模拟实现AVL树&红黑树
java·数据结构·算法
生锈的键盘6 小时前
推荐算法实践:交叉特征的理解
算法
小龙报6 小时前
【51单片机】从 0 到 1 玩转 51 蜂鸣器:分清有源无源,轻松驱动它奏响新年旋律
c语言·数据结构·c++·stm32·单片机·嵌入式硬件·51单片机
乌萨奇也要立志学C++7 小时前
【洛谷】BFS 求解最短路:从马的遍历到迷宫问题的实战解析
算法·宽度优先
石去皿7 小时前
【嵌入式就业6】计算机组成原理与操作系统核心机制:夯实底层基础
c++·面试·嵌入式
王老师青少年编程7 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(完善程序第1题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组