Description
Given a preorder sequence of a binary tree, find the height of the binary tree.
Input
The input consists of two parts
. The first part: a positive integer n, which means there are n binary trees
. The second part: includes n lines, each line represents the preorder traversal sequence of a binary tree, and the null pointer is occupied by the character ^
Output
n lines, each with an integer, representing the height of the corresponding binary tree
Sample Input
2
ABC^^^^
AB^^^
Sample Output
3
2
Note the newlines!
Note the newlines!
Note the newlines!
Nothing else.
#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();//newline while(flag--) { BiTree T; Q_CreatTree(&T);//Preorder traversal to create a binary tree getchar();//newline int deep=TreeDeep(T); printf("%d\n",deep); } } void Q_CreatTree(BiTree *T)//Preorder traversal to build a binary tree { 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)//Seek the depth of the tree { 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; }