【id:172】【5分】F. DS树--二叉树高度

文章详细介绍了如何使用C++编程语言实现二叉树的高度计算,通过层次遍历方法,对给定的先序遍历结果进行解析并计算出二叉树的高度。
摘要由CSDN通过智能技术生成

【二叉树新体会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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值