0
点赞
收藏
分享

微信扫一扫

用递归法把二叉树的叶子结点按从左到右的顺序连成一个单链表

夕阳孤草 2022-08-04 阅读 56


一、例子

用递归法把二叉树的叶子结点按从左到右的顺序连成一个单链表_结点

上图中的二叉树的叶子结点,按从左到右的顺序连成的单链表如下图所示:

用递归法把二叉树的叶子结点按从左到右的顺序连成一个单链表_flink_02

二、定义数据结构

typedef struct tree
{
int data;
struct tree *left;
struct tree *right;
}node, *pnode;

pnode firstLeaf; // 记录叶子链表的第一个叶子结点
pnode pcur; // 记录叶子链表的当前结点

三、核心算法

void leafLink(pnode root)
{
if(!root)
{
return;
}

if(NULL == root->left && NULL == root->right)
{
if(NULL == firstLeaf)
{
firstLeaf = root; // 保存找到的第一个叶子结点(k指针)
pcur = firstLeaf;
}
else
{
// 链接时用叶子结点的rchild域存放指针
pcur->right = root;
pcur = pcur->right;
}
}

if(root->left)
{
leafLink(root->left);
}

if(root->right)
{
leafLink(root->right);
}
}

四、完整代码

#include <stdio.h>
#include <malloc.h>

typedef struct tree
{
int data;
struct tree *left;
struct tree *right;
}node, *pnode;

pnode firstLeaf;
pnode pcur;

pnode createTreeNode(int data)
{
pnode n=(pnode)malloc(sizeof(pnode));
n->data = data;
n->left = NULL;
n->right = NULL;

return n;
}

void inorder(pnode p)
{
if (NULL == p)
{
return;
}
inorder(p->left);
printf("%d ", p->data);
inorder(p->right);
}

void leafLink(pnode root)
{
if(!root)
{
return;
}

if(NULL == root->left && NULL == root->right)
{
if(NULL == firstLeaf)
{
firstLeaf = root; // 保存找到的第一个叶子结点(k指针)
pcur = firstLeaf;
}
else
{
// 链接时用叶子结点的rchild域存放指针
pcur->right = root;
pcur = pcur->right;
}
}

if(root->left)
{
leafLink(root->left);
}

if(root->right)
{
leafLink(root->right);
}
}

int main()
{
pnode p1 = createTreeNode(7);
pnode p2 = createTreeNode(1);
pnode p3 = createTreeNode(9);
pnode p4 = createTreeNode(5);
pnode p5 = createTreeNode(8);
pnode p6 = createTreeNode(3);
pnode p7 = createTreeNode(6);
pnode p8 = createTreeNode(2);
pnode p9 = createTreeNode(4);

p1->left = p2;
p1->right = p3;

p2->right = p4;

p3->left = p5;

p4->left = p6;
p4->right = p7;

p6->left = p8;
p6->right = p9;

printf("The inorder traversal sequence: ");
inorder(p1);
printf("\n");

leafLink(p1);
printf("The leaves linked list sequence: ");
while(firstLeaf)
{
if(firstLeaf->right)
{
printf("%d-->",firstLeaf->data);
}
else
{
printf("%d",firstLeaf->data);
}
firstLeaf=firstLeaf->right;
}
printf("\n");

return 0;
}

运行结果

The inorder traversal sequence: 1 2 3 4 5 6 7 8 9
The leaves linked list sequence: 2-->4-->6-->8



举报

相关推荐

0 条评论