求二叉树的深度和宽

Description

(1)根据教材中算法6.4所示的算法,按照给出的先序序列建立二叉链表表示的二叉树(结点数不超过26)。
(2)计算该二叉树的繁茂程度。
一颗二叉树的繁茂程度为二叉树的宽度与高度的乘积,二叉树的宽度为各层节点数的最大值。

Input

包含多组测试数据。每组测试数据一行,给出二叉树的先序遍历序列(至少1个结点)。

Output

输出二叉树的繁茂程度。

Sample Input

ABC^^DE^G^^F^^^
A^^
AB^^C^^

Sample Output

10
1
4

分析:本题要求计算二叉树的繁茂程度,也就是计算二叉树宽度和深度的成绩,进而简化到求二叉树的深度和宽度。二叉树的深度比较好求,首先判断树是否为空,如果不为空,那么二叉树的深度即为1+max(左子树的深度,右子树的深度)。二叉树的宽度就要通过队列来求了,对二叉树进行层次遍历,同一层的进队,求出该层宽度,找出最大的。

参考代码:
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<iostream>

using namespace std;
typedef struct BiTNode{
    char d;
    struct BiTNode *l;
    struct BiTNode *r;
}*BiTree,BiTreeNode;
char ch;
bool flag;

void CreatBiTree( BiTree &T)//创建二叉树
{
    char tmp;
    if( flag)
        scanf("%c",&tmp);
    else
    {
        tmp = ch;
        flag = 1;
    }

    if( tmp == '^')
        T = NULL;
    else
    {
        T = new BiTreeNode;
        T->d = tmp;
        CreatBiTree(T->l);
        CreatBiTree(T->r);
    }
}

int getdepth( BiTree T)//获取二叉树的深度
{
    if( T == NULL)
    {
        //printf("t=null\n");
        return 0;
    }

    else
    {
        //printf("tt\n");
        int left = getdepth(T->l);
        int right = getdepth(T->r);
        return 1+max(left,right);
    }

}

int getwidth( BiTree T)//求二叉树的宽度
{
    if( T == NULL)
        return 0;
    queue<BiTree> q;
    q.push(T);
    int maxwidth = 1;
    while( true)
    {
        int len = q.size();
        if( len == 0)
            break;
        while( len > 0)
        {
            BiTree t = q.front();
            q.pop();
            len--;
            if( t->l != NULL)
                q.push( t->l);
            if( t->r != NULL)
                q.push( t->r);
        }
        if( q.size() > maxwidth)
            maxwidth = q.size();
    }
    return maxwidth;

}

int main()
{
    while( ~scanf("%c",&ch))
    {
        if( ch == '\n')
            continue;
        BiTree T = NULL;
        flag = 0;
        CreatBiTree( T);
        int a = getdepth( T);
        int b = getwidth( T);
        //printf("a = %d, b = %d\n",a,b);
        printf("%d\n",a*b);

    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值