代码随想录算法训练营第十五天-二叉树-110.平衡二叉树

  • 所谓平衡二叉树是指任意子树的高度差不超过1
  • 目前所学习的有关二叉树的问题,都是基于二叉树的遍历顺序来实现的
cpp 复制代码
#include <iostream>
#include <sstream>
#define LEN 10009

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(): val(0), left(nullptr), right(nullptr) {}
    TreeNode(int v): val(v), left(nullptr), right(nullptr) {}
    TreeNode(int v, TreeNode* l, TreeNode* r): val(v), left(l), right(r) {}
};

class Solution {
public:
    TreeNode* getTree() {
        TreeNode* tnArr[LEN] {nullptr};
        std::string str_content;
        std::getline(std::cin, str_content);
        std::stringstream ss {str_content};
        for (int index = 0; ss >> str_content; ++index) {
            if (str_content != "null")
                tnArr[index] = new TreeNode(stoi(str_content));
            else
                tnArr[index] = nullptr;
            if (index > 0) {
                if (index % 2 == 1)
                    tnArr[index / 2]->left = tnArr[index];
                else
                    tnArr[(index - 1) / 2]->right = tnArr[index];
            }
        }
        return tnArr[0];
    }
    bool isBalanced(TreeNode* root) {
        if (getHeight(root) != -1)
            return true;
        return false;
    }
    int getHeight(TreeNode* node) {
        if (node == nullptr)
            return 0;
        int left_height = getHeight(node->left);
        if (left_height == -1)
            return -1;
        int right_height = getHeight(node->right);
        if (right_height == -1)
            return -1;
        if (std::abs(left_height - right_height) > 1)
            return -1;
        return 1 + std::max(left_height, right_height);
    }
};

int main()
{
    Solution s;
    TreeNode* root = s.getTree();// 通过录入一行数据,就可以生成树形
    std::cout << s.isBalanced(root) << std::endl;
    return 0;
}
相关推荐
luj_17681 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
木木子223 小时前
# 鸿蒙 ArkTS 实战:秒表 Stopwatch(示例 5)
数据结构·华为·list·harmonyos
geats人山人海4 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
漂流瓶jz5 小时前
UVA-12627 奇怪的气球膨胀 题解答案代码 算法竞赛入门经典第二版
算法·图论·递归·aoapc·算法竞赛入门经典·uva·12627
jarvisuni5 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
kobesdu5 小时前
流形上的优化:SO(3)与SE(3)的广义加减法在FAST-LIO中如何简化状态估计
人工智能·算法·fastlio
白狐_7985 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
乐观勇敢坚强的老彭5 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶5 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
Hi李耶6 小时前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展