代码随想录算法训练营第十五天-二叉树-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;
}
相关推荐
HjhIron3 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩4 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹6 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术10 小时前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望11 小时前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰11 小时前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage1 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn1 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法