二叉树中序线索化及查找某一结点的前驱,后继结点

#include<iostream>

using namespace std;

#define MAX 1500

//二叉树定义
typedef struct BiTreeNode{
  char data;
  BiTreeNode *lChild;
  BiTreeNode *rChild;
  int lTag,rTag;
}BiTreeNode;

//全局变量
BiTreeNode *pre =NULL;
BiTreeNode *point[MAX+1]; //构建二叉树时辅助,用于定位子节点

//构建二叉树
BiTreeNode *CreateBiTree()
{
  BiTreeNode *root=(BiTreeNode *)malloc(sizeof(BiTreeNode));
  int i,j;char data;
  cin>>i>>data;
  while(i!=0&&data!='#')
  {
    BiTreeNode *newNode=(BiTreeNode *)malloc(sizeof(BiTreeNode));
    newNode->data=data;
    newNode->lTag=0;newNode->rTag=0;
    newNode->lChild=NULL;newNode->rChild=NULL;
    point[i]=newNode; 
    if(i==1)    //为二叉树根节点
    {
      root=point[1];
    }
    else
    {
      j=i/2;
     if(i%2==0)   //为左孩子结点
     {
        point[j]->lChild=newNode;
      }
      else
     {
        point[j]->rChild=newNode;
      }
     }
     cin>>i>>data;
  }
  return root;
}

//中序线索化二叉树,pre初始化为NULL
void Inthread(BiTreeNode *root)
{
  if(root!=NULL)
  {  
     Inthread(root->lChild);
     if(root->lChild==NULL)
     {
      root->lTag=1;root->lChild=pre;
     }
     if(pre!=NULL&&pre->rChild==NULL)
     {
      pre->rTag=1;pre->rChild=root;
     }
     pre=root;
     Inthread(root->rChild);
  }
}


//查找结点p的前驱结点
BiTreeNode *InPre(BiTreeNode *p)
{
  if(p->lTag==1)return p->lChild;
  BiTreeNode *q=p->lChild;
  if(q==NULL){
     cout<<"无前驱结点\n";
     return NULL;
  }
  while(q->rTag!=1)
  {
    q=q->rChild;
  }
  return q;
}

//查找结点p的后继结点
BiTreeNode *InSub(BiTreeNode *p)
{
  if(p->rTag==1)return p->rChild;
  BiTreeNode *q=p->rChild;
  if(q==NULL){
     cout<<"无后继结点\n";
     return NULL;
  }
  while(q->lTag!=1)
  {
    q=q->lChild;
  }
  return q;
}


int main()
{
  char cmd;int index;
  do{
     BiTreeNode *root=CreateBiTree();
     Inthread(root);
     cout<<"输入您要查找的结点,序号index\n";
     cin>>index;
     BiTreeNode *nodePre=InPre(point[index]);
     BiTreeNode *nodeSub=InSub(point[index]);
     if(nodePre!=NULL)
        cout<<"结点"<<index<<"的前驱结点的值为"<<nodePre->data<<"\n";
     if(nodeSub!=NULL)
       cout<<"结点"<<index<<"的后继结点的值为"<<nodeSub->data<<"\n";
     cout<<"继续吗Y/y?\n";
     cin>>cmd;
  }while(cmd=='Y'||cmd=='y');
  return 0;
}
 
  • 2
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值