建立中序线索二叉树

本文介绍了一种使用C语言实现二叉树的方法,包括二叉树的创建过程及中序遍历算法。通过递归的方式构建二叉树,并采用中序线索化方式遍历树结构。

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

#include "stdio.h"
#define OK 1
#define LEN sizeof(struct BiTNode)
#define TRUE 1
#define FALSE 0
#define Link 0
#define Thread 1
struct BiTNode    //定义一个二叉树结点
{
 char data;
 struct BiTNode *lchild,*rchild;
 int LTag,RTag;
};

struct BiTNode *CreateTree(char [],int);

struct  BiTNode *pre;
main()
{
 struct BiTNode *root;  //定义两个二叉树的根节点
 int chi=1;      //用作建立二叉树的游标
 char ch1[10]="abcdefghi";    //定义两个二叉树
 root=(struct BiTNode *)malloc(LEN);
 root->lchild=CreateTree(ch1,chi);
}

struct BiTNode *CreateTree(char ch[],int chi)      //按定义建立二叉树
{
 if(chi>=10)
 return NULL;
 else
 {
  struct BiTNode *root;
  root=(struct BiTNode *)malloc(LEN);
  root->data=ch[chi-1];
  root->LTag=root->RTag=0;
  root->lchild=CreateTree(ch,chi*2);
  root->rchild=CreateTree(ch,chi*2+1);
  return root;
 }
}

InOrderTraverse(struct BiTNode *root)         //中序遍历二叉树
{
 struct BiTNode *Thrt;
 Thrt=(struct BiTNode *)malloc(LEN);
 Thrt->LTag=Link;
 Thrt->RTag=Thread;
 Thrt->rchild=Thrt;
 if(!root->lchild)
 Thrt->lchild=Thrt;
 else
 {
  Thrt->lchild=root->lchild;
  pre=Thrt;
  InThreading(root);
  pre->rchild=Thrt;
  pre->RTag=Thread;
  Thrt->rchild=pre;
 }
 return OK;
}

InThreading(struct BiTNode *p)
{
 if(!p)
 {
  InThreading(p->lchild);
  if(!p->lchild)
  {
   p->LTag=Thread;
   p->lchild=pre;
  }
  if(!pre->rchild)
  {
   pre->RTag=Thread;
   pre->rchild=p;
  }
  pre=p;
  InThreading(p->rchild);
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值