6-20 数据结构考题 - 先序遍历二叉树

以二叉链表作存储结构,建立一棵二叉树。 输出该二叉树的先序遍历序列,求出该二叉树的深度,并统计其叶子结点数。

二叉链表的类型描述

typedef char ElemType;
typedef  struct  BiNode
{  ElemType  data;
    struct  BiNode   *lchild,*rchild;
}BiNode,*BiTree;  

 下面给出了 二叉树遍历 函数的大部分内容,但缺少了一部分(以下划线____标识出来的部分)。

请先将以下代码中画横线的部分补充完整,然后将完整的函数PreOrder,CountLeaf,Depth 提交系统,完成题目要求的功能。

函数接口定义:

void PreOrder(BiTree T)

    if (T) 
    { 
        cout<< ____ ;  
        PreOrder( ____ );  
        PreOrder( ____ ); 
    }
}

// 统计叶子节点数
// 叶子节点个数通过参数 n 返回
void CountLeaf(BiTree T, int &n)

    if (T) 
    { 
        if ( ____ )   n++;
        CountLeaf( ____ , n);
        CountLeaf( ____ , n);
    }
}

// 计算二叉树高度
// 高度通过 dep 返回
void Depth(BiTree T, int &dep)

    int  dl,dr;
    if ( ____ )  dep=0;
    else 
    { 
        Depth( ____ , ____ );         
        Depth( ____ , ____ );
        dep=dl>dr? ____ : ____;
    }
}

测试主程序样例:

int main()

    BiTree T;  int n=0,dep;
    CreateBiTree(T);
    cout<<"PreOrder:";  PreOrder(T);  cout<<endl;
    Depth(T,dep);  cout<<"Depth:"<<dep<<endl;
    CountLeaf(T,n);  cout<<"Leaf:"<<n<<endl;
    return 0;
}

 

输入格式:

输入一个二叉树的先序序列,孩子为空的位置以#替代。

输出格式:

输出分3行

第一行 先序遍历序列

第二行 二叉树深度

第三行 叶子结点数

其中遍历过程中按访问顺序打印出结点的内容时,字符间均无间隔。 具体格式参看输出样例。

对于下图中给出的二叉树:

输入样例:

ABD##FE###CG#H##I##

 输出样例:

PreOrder:ABDFECGHI
Depth:4
Leaf:4

 

 

void PreOrder(BiTree T)
{ 
    if (T) 
    { 
        cout<< T->data ;  
        PreOrder( T->lchild );  
        PreOrder( T->rchild ); 
    }
}

// 统计叶子节点数
// 叶子节点个数通过参数 n 返回
void CountLeaf(BiTree T, int &n)
{ 
    if (T) 
    { 
        if ( !T->lchild&&!T->rchild )   n++;
        CountLeaf( T->lchild , n);
        CountLeaf( T->rchild , n);
    }
}

// 计算二叉树高度
// 高度通过 dep 返回
void Depth(BiTree T, int &dep)
{ 
    int  dl,dr;
    if ( !T )  dep=0;
    else 
    { 
        Depth( T->lchild , dl );
        Depth( T->rchild , dr );
        dep=dl>dr? dl+1 : dr+1;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

THK-J

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值