首页 > 学院 > 开发设计 > 正文

求二叉树的深度和宽

2019-11-08 01:40:43
字体:
来源:转载
供稿:网友

Description

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

Input

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

Output

输出二叉树的繁茂程度。

Sample Input

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

Sample Output

1014分析:本题要求计算二叉树的繁茂程度,也就是计算二叉树宽度和深度的成绩,进而简化到求二叉树的深度和宽度。二叉树的深度比较好求,首先判断树是否为空,如果不为空,那么二叉树的深度即为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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表