题目描述
给出一棵二叉树,求它的高度。二叉树的创建采用前面实验的方法。
注意,二叉树的层数是从1开始
输入
第一行输入一个整数t,表示有t个二叉树
第二行起输入每个二叉树的先序遍历结果,空树用字符‘0’表示,连续输入t行
输出
每行输出一个二叉树的高度
#include<bits/stdc++.h>
using namespace std;
struct YoRha{
char data;
YoRha *left,*right;
};
class YoRha_type{
public:
int pos;
YoRha *root;
string a;
YoRha_type(string x){
a=x;
pos=0;
}
YoRha*getdata(){
YoRha * root =new YoRha;
if(a[pos]=='0') {
pos++;
return NULL;
}
root->data=a[pos++];
root->left=getdata();
root->right=getdata();
return root;
}
void outside(YoRha *a){
cout<<a->data<<' ';
if(a->left!=NULL){
outside(a->left);
}
if(a->right!=NULL){
outside(a->right);
}
}
int hei(YoRha *a){
if(a->left==NULL && a->right==NULL){
return 1;
}int ansl=0,ansr=0;
if(a->left)
ansl+=hei(a->left);
if(a->right)
ansr+=hei(a->right);
if(ansl>ansr){
return ansl+1;
}else return ansr+1;
}
};
int main(){
int n;cin>>n;
while(n--){
string a; cin>>a;
YoRha_type two(a);
YoRha *root;
root=two.getdata();
//two.outside(root);
//cout<<endl;
cout<<two.hei(root)<<endl;
}
}
哦通过递归解题