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;
}
相关推荐
林森lsjs18 小时前
【日耕一题】5. 青春常数(17届蓝桥杯C++B组第一题)
算法·蓝桥杯
laplaya18 小时前
C++大型项目组件通信与依赖管理实践
c++·log4j·apache
Tisfy18 小时前
LeetCode 3838.带权单词映射:求和、取模、拼接(附python一行版)
python·算法·leetcode·字符串·题解·模拟·取模
春栀怡铃声18 小时前
【C++修仙录03】进阶篇:多态
c++
め.19 小时前
GJK算法实现细节
算法
小灰灰搞电子19 小时前
C++ boost::container 详解:高性能容器库完全指南
开发语言·c++·boost
AI科技星19 小时前
第六卷:量天尺传奇(几何学)
网络·人工智能·算法·概率论·学习方法·几何学·拓扑学
Y_Bk19 小时前
第十七届蓝桥杯C/C++A组省赛
c语言·数据结构·c++·算法·蓝桥杯
Brilliantwxx19 小时前
【C++】 C++11 知识点梳理(上)
开发语言·c++
帅小伙―苏19 小时前
力扣76最小覆盖子串
算法·leetcode