#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");
}