c/c++实现线索二叉树及其中序遍历和查找

本文介绍如何使用C++实现线索二叉树的数据结构,并提供了中序遍历及节点查找的方法。文中详细展示了如何通过递归的方式进行二叉树的线索化处理,以及如何在遍历时利用线索找到前驱和后继节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c/c++实现线索二叉树及其中序遍历和查找

#include<stdio.h>

#include<stdlib.h>


typedef char DataType;
typedef struct {
int ltag,rtag;
DataType data;
struct node *lchild,*rchild;
}ThreadNode,*ThreadTree;




//inorder thread tree 
void inThread(ThreadTree t,ThreadTree pre)//before being called pre is null
{
if(t)
{
inThread(t->lchild,pre);
if(!t->lchild)
{
t->ltag=1;
t->lchild=pre;
}
if(!t->rchild)
 t->rtag=1;
if(pre && pre->rtag==1)
 pre->rchild=t;
pre=t;
inTread(t->rchild,pre);
}
}




ThreadTree inPreNode(ThreadTree p)//get the prenode of p
{
ThreadTree pre;
pre=p->lchild;
if(p.ltag==0)
while(pre->rtag==0) pre=pre->rchild;
return pre;
}


ThreadTree inPostNode(ThreadTree p)//get the postnode of p
{
ThreadTree post;
post=p->rchild;
if(p.rtag==0)
while(post->ltag==0) post=post->lchild;
return post;
}




//traverse the thread tree
void inOrder(ThreadTree t)
{
ThreadTree p;
if(t)
{
p=t;
while(p->ltag==1) p=p->lchild;
while(p)
{
visit(p->data);
p=inPostNode(p);//get the postnode of p
}
}
}


//search for node of x
ThreadTree inOrder(ThreadTree t,DataType x)
{
ThreadTree p;
if(t)
{
p=t;
while(p->ltag==1) p=p->lchild;
while(p)
{
if(p->data==x)
 break;
p=inPostNode(p);//get the postnode of p
}
}
return p;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值