求树的高(深度)

Description

给定一颗二叉树的先序序列,求该二叉树的高。

Input

输入包括两部分
第一部分:一个正整数n,代表有n颗二叉树
第二部分:包括n行,每行代表一颗二叉树的先序遍历序列,空指针用字符^占位

Output

n行,每行一个整数,代表对应二叉树的高度

Sample Input

2
ABC^^^^
AB^^^

Sample Output

3
2

请注意换行符!

请注意换行符!

请注意换行符!

别的没啥。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
    char ch;
    struct node *Lchild;
    struct node *Rchild;
}BiTiNode,*BiTree;
void Q_CreatTree(BiTree *T);
void Q_Traverse(BiTree T);
int TreeDeep(BiTree T); 
int main(void)
{
    int flag;
    scanf("%d",&flag);
    getchar();//换行符 
    while(flag--)
    {
        BiTree T;
        Q_CreatTree(&T);//前序遍历创建二叉树
        getchar();//换行符 
        int deep=TreeDeep(T);
        printf("%d\n",deep);
    }
}
void Q_CreatTree(BiTree *T)//前序遍历建立二叉树 
{
    char str;
    str=getchar();
    if(str=='^')
    {
        *T=NULL;
    }
    else
    {
        (*T)=(BiTree)malloc(sizeof(BiTiNode));
        (*T)->ch=str;
        Q_CreatTree( &( (*T)->Lchild ) );
        Q_CreatTree( &( (*T)->Rchild ) );
    }
}
int TreeDeep(BiTree T)//求树的深度
{
    int n=0;
    if(T)
    {
        int L=TreeDeep(T->Lchild);
        int R=TreeDeep(T->Rchild);
        n=L+1>R+1?L+1:R+1;
    }
    return n;
 } 

猜你喜欢

转载自blog.csdn.net/holly_z_p_f/article/details/80114631