数据结构——List Leaves(题目来源于数据结构(浙江大学)题集)

题目: List Leaves

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

题目分析:大致意思是输入一棵树,输出为从上到下从左到右输出树中的叶子节点。经过验证题中示例,确实没理解错。

思路:1.建树返回根节点以便索引;

           2.层序遍历寻找叶节点并打印;

#include <stdio.h>
typedef int Tree;
#define MaxSize 20
#define Null -1
int M = 0;
struct TreeNode {               //数组用来存储二叉树 
	int data;
	Tree left;
	Tree right;
}tr[MaxSize];
int BuildTree(struct TreeNode T[])
{
	int N, i;
	int check[10] = { 0 };
	int root;
	scanf("%d", &N);
	getchar();  
	if (N)
	{
		for (i = 0; i < N; i++) {
			char l, r;
			scanf("%c %c", &l, &r);              //读入左右孩子 
			getchar();
			if (l == '-' && r == '-')M++;        //叶子节点个数 
			tr[i].data = i;                     //节点数据 
			if (l != '-')
			{
				tr[i].left = l - '0';
				check[tr[i].left] = 1;
			}
			else tr[i].left = Null;
			if (r != '-')
			{
				tr[i].right = r - '0';
				check[tr[i].right] = 1;
			}
			else tr[i].right = Null;
		}
		for (i = 0; i < N; i++)                     //根节点 
		{
			if (check[i] == 0)
				break;
		}
		root = i;
	}
	return root;

}
void LevelNode(int root)
{
	int queue[10] = { 0 }, rear = -1, front = -1;   //设置队列,按层次输出 
	struct TreeNode p;
	queue[++rear] = root;                         //队尾插入根节点 
	
	while (front != rear) {                       //队列不为空 
		p =tr[queue[++front]];                   //队头取出节点 
		if (p.left != -1)queue[++rear] = p.left;   //队尾插入左孩子
		if (p.right != -1)queue[++rear] = p.right; //队尾插入右孩子 
		if (p.left == -1 && p.right == -1) {          //输出叶子节点 
			printf("%d", p.data);
			M--;
			if (M)printf(" ");
		}
	}
}
int main()
{
	int r = BuildTree(tr);
	LevelNode(r);
	return 0;
}

这里的队列直接用数组简单粗暴的处理。(不懂,学习)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值