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;
}
相关推荐
luj_17682 小时前
残熵算法实时化三大瓶颈突破
c语言·开发语言·网络·经验分享·算法
mCell2 小时前
你以为短链接只是 Hash + 301/302?
后端·算法·架构
远离UE43 小时前
UE5 compute shader 原子加
开发语言·c++·ue5
C+-C资深大佬3 小时前
C++ 显式类型转换详解:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
KaMeidebaby4 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
luj_17684 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
取地址符5 小时前
C++学习笔记(基于learn-cxx)(1)
c++·经验分享·笔记·学习
tmlx3I0815 小时前
高光谱拼接算法(六)RANSAC 误匹配剔除
人工智能·算法·机器学习
不相心 -w-5 小时前
基础-滑动窗口-(定长 | 不定长)
算法
思麟呀5 小时前
C++17(三)if constexpr+折叠表达式
开发语言·c++