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;
}
相关推荐
炸膛坦客6 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
I_LPL6 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱7 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073217 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
炸膛坦客8 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_831824968 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~8 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you9 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018729 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563249 小时前
模板代码生成工具
开发语言·c++·算法