用二级指针求解二叉树根节点

写了这个算法,总算有点理解二级指针了。

 

#include  < stdio.h >
#include 
< stdlib.h >
#define  OVERFLOW -2
#define  INFEASIBLE -1
#define  ERROR 0
#define  OK 1
#define  TRUE 1
#define  FALSE 0

typedef 
int  TElemType;
TElemType Nil
= 0 ;

typedef 
struct  BiTNode
{
    TElemType data;
    BiTNode 
*lchild,*rchild;
}
BiTNode, * BiTree;

int  InitBiTree(BiTree  * T)
{
    
*T=NULL;
    
return OK;
}


void  CreateBiTree(BiTree  * T)
{
    TElemType ch;
    scanf(
"%d",&ch);
    
if(ch==Nil)
        (
*T)=NULL;
    
else
    
{
        (
*T)=(BiTree)malloc(sizeof(BiTNode));
        
if(!(*T))
            exit(OVERFLOW);
        (
*T)->data=ch;
        CreateBiTree(
&(*T)->lchild);
        CreateBiTree(
&(*T)->rchild);
    }

}


int  BiTreeEmpty(BiTree  * T)
 
// 初始条件: 二叉树T存在
   
// 操作结果: 若T为空二叉树,则返回TRUE,否则FALSE
   if(*T)
     
return FALSE;
   
else
     
return TRUE;
 }


 TElemType Root(BiTree 
* T)
 
// 初始条件: 二叉树T存在。操作结果: 返回T的根
   if(BiTreeEmpty(&(*T)))
     
return Nil;
   
else
     
return (*T)->data;
 }


 
void  main()
 
{
     TElemType e;
     BiTNode
* T;
     InitBiTree(
&T);
     printf(
"请先序输入二叉树(如:1 2 0 0 0表示1为根结点,2为左子树的二叉树) ");
     CreateBiTree(
&T);
     e
=Root(&T);
     
if(e==0)printf("二叉树无根节点!/n");
     
else
     printf(
"二叉树根结点:%d ",e);
 }

因为在CreateBiTree() 中会分配内存给数据,所以主函数内不进行内存分配,即不按如下定义:

BiTNode T;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值