将二叉树的叶子结点从左到右连成一个单链表

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

constexpr auto NoLoRNode = -1;//代表没有左or右结点
typedef int DataType;

typedef struct TreeNode {
	DataType Data;
	TreeNode* Left;
	TreeNode* Right;
}*BinTree,*TreeList;

BinTree CreateBinTree(BinTree BT)
{
	int DATA;
	scanf_s("%d", &DATA);

	if (DATA != NoLoRNode)
	{
		BT = (BinTree)malloc(sizeof(TreeNode));
		BT->Data = DATA;

		printf("InPut %d -> Left:", BT->Data);
		BT->Left = CreateBinTree(BT->Left);

		printf("InPut %d -> Right:", BT->Data);
		BT->Right = CreateBinTree(BT->Right);
	}
	else
		BT = nullptr;

	return BT;
}

TreeList Leaf_List(BinTree BT)
{
	static TreeList Head = nullptr;
	static TreeList Pre = nullptr;

	if (BT)
	{
		if (!BT->Left && !BT->Right)
		{
			if (!Pre)
			{
				Head = BT;
				Pre = BT;
			}
			else
			{
				Pre->Right = BT;
				Pre = BT;
			}

			Pre->Right = NULL;
		}
		Leaf_List(BT->Left);
		Leaf_List(BT->Right);
	}

	return Head;
}

int main()
{
	printf("InPut Root:");

	BinTree BT = nullptr;
	BT = CreateBinTree(BT);

	TreeList L = Leaf_List(BT);

	printf("\nThe Tree-List of This BinTree is:");
	while (L)
	{
		printf("%d ", L->Data);
		L = L->Right;
	}
	printf("\n");
}

 将二叉树的叶子结点从左至右连成一个单链表,首先要实现从左到右顺序遍历叶子结点,然后将它们连成一个单链表。而前/中/后序遍历都是符合条件的,所以这道题本质就是前/中/后序遍历的代码里面再加一个对于叶子结点的操作(连成单链表)。思路到了这个地方,相信只要你会写前/中/后序遍历,这道题就迎刃而解了。

#include<stdio.h>
#include<stdlib.h>

#define null -1
typedef int DataType;

typedef struct TreeNode {
	DataType Data;
	struct TreeNode* Left;
	struct TreeNode* Right;
}*BinTree, * TreeList;

BinTree CreateBinTree(BinTree BT)
{
	int DATA;
	scanf_s("%d", &DATA);

	if (DATA != null)//假如输入的数据为null,代表此节点没有左结点或者右节点,本程序先将null定义为-1;
	{
		BT = (BinTree)malloc(sizeof(struct TreeNode));
		BT->Data = DATA;

		printf("InPut %d -> Left:", BT->Data);
		BT->Left = CreateBinTree(BT->Left);

		printf("InPut %d -> Right:", BT->Data);
		BT->Right = CreateBinTree(BT->Right);
	}
	else
		BT = NULL;

	return BT;
}

BinTree Head;
BinTree Pre = NULL;

BinTree Leaf_List(BinTree BT)
{
	if (BT)
	{
		
		if (!BT->Left && !BT->Right)
		{
			if (!Pre)
			{
				Head = BT;
				Pre = BT;
			}

			else
			{
				Pre->Right = BT;
				Pre = BT;
			}
		}

		Leaf_List(BT->Left);
		Leaf_List(BT->Right);

		Pre->Right = NULL;
	}

	return Head;
}

int main()
{
	printf("InPut Root:");

	BinTree BT = (BinTree)malloc(sizeof(struct TreeNode));
	BT = CreateBinTree(BT);

	TreeList L = Leaf_List(BT);

	printf("\nThe TreeList of this BinTree is:");
	while (L)
	{
		printf("%d ", L->Data);
		L = L->Right;
	}
	printf("\n");
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值