题目描述
计算二叉树的深度,空树深度为 0。
输入格式
第 1 行为测试用例数 m。 第 2 行开始,每一行是一个含空结点的二叉树的前序遍历序列(序列长度不小于 1,不大于 1024),空结点用 # 表示。非空结点的符号为字母或数字。
输出格式
对每一个测试用例,输出一行对应二叉树的深度。
输入样例
2
ab##c##
a#b#c##
输出样例
2
3
代码展示
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
struct BiNode{
string data;
BiNode *lchild,*rchild;
};
using BiTree=BiNode*;
int DestroyBiTree(BiTree &T){//销毁二叉树
if(T==nullptr) return 0;
DestroyBiTree(T->lchild);
DestroyBiTree(T->rchild);
delete T;
T=nullptr;
return 0;
}
int GetDepth(BiTree T){//求深度
if(T==nullptr) return 0;
return max(GetDepth(T->lchild),GetDepth(T->rchild))+1;
}
//根据带虚结点的前序遍历串构造二叉树
char *CreateBiTree(BiTree &T,char *str){
if(*str=='#'){
T=nullptr;
return str+1;
}
T=new BiNode;
T->data=*str;
char * strAfterLeft=CreateBiTree(T->lchild,str+1);
char * strAfterRight=CreateBiTree(T->rchild,strAfterLeft);
return strAfterRight;
}
int main(){
//freopen("/config/workspace/test/test","r",stdin);
int n;
cin>>n;
while(n--){
string s;
cin>>s;
BiTree tree=nullptr;
CreateBiTree(tree,&s[0]);
int depth=GetDepth(tree);
cout<<depth<<endl;
DestroyBiTree(tree);
}
return 0;
}