【二叉树新体会uwu,终于理解层次遍历的使用过程以及原理uwu】
题目描述
给出一棵二叉树,求它的高度。
注意,二叉树的层数是从1开始
输入
第一行输入一个整数t,表示有t个二叉树
第二行起输入每个二叉树的先序遍历结果,空树用字符‘0’表示,连续输入t行
输出
每行输出一个二叉树的高度
#include <iostream>
#include <queue>
//#include "math.h"
#include "algorithm"
#include "stack"
#include "iomanip"
using namespace std;
int mmax=1000;
queue<char> child;
queue<char> parents;
class node{
public:
char data;
node *left= nullptr;
node *right= nullptr;
node *parent = nullptr;
int ceng;
};
queue<node*> q;
node* Create(string str,int& index){
if(str[index]=='0'){
return nullptr;
}
node* tmp=new node;
tmp->data=str[index];
tmp->left= Create(str,++index);
tmp->right= Create(str,++index);
if(tmp->left)
tmp->left->parent=tmp;
if(tmp->right)
tmp->right->parent=tmp;
return tmp;
}
void cengci(node *root){
if(!root)
return;
while(!q.empty()){
if(root->left)
q.push(root->left);
if(root->right)
q.push(root->right);
cout<<q.front()->data;
q.pop();
cengci(q.front());
}
}
void set_ceng(node* root){
if(!root)
return;
if(root->right== nullptr &&root->left== nullptr){
root->ceng = 1;
return;
}
if(root->left == nullptr){
set_ceng(root->right);
root->ceng = root->right->ceng+1;
return;
}
if(root->right == nullptr){
set_ceng(root->left);
root->ceng = root->left->ceng+1;
return;
}
set_ceng(root->left);
set_ceng(root->right);
root->ceng = max(root->left->ceng, root->right->ceng)+1;
}
int main() {
int t;
cin>>t;
while(!child.empty())
child.pop();
while(t--){
string str;
cin>>str;
int index=0;
node* root = Create(str,index);
set_ceng(root);
cout<<root->ceng<<endl;
}
return 0;
}