代码随想录算法训练营第十五天-二叉树-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;
}
相关推荐
linx29518 分钟前
单元三 · 那 C 的底层知识怎么办
c语言·开发语言·数据结构·c++·嵌入式硬件
数据知道1 小时前
国密算法实战——SM2/SM3/SM4 在国产系统中的应用
网络·算法·安全·网络安全·密码学·哈希算法
zander2581 小时前
LeetCode 128. 最长连续序列
数据结构·算法
linx2951 小时前
单元四 · 对称认知·上:内存与指针
c语言·开发语言·数据结构·嵌入式硬件·算法
-dzk-2 小时前
【二叉树】LC 236.二叉树的最近公共祖先
数据结构·二叉树
午彦琳2 小时前
2026.9.11
数据结构·python·算法
careathers3 小时前
【数据结构】链表
数据结构·链表
302wanger3 小时前
蛋炒饭周刊 · 第 1 期(2026-09-07至2026-09-11)
算法
shehuiyuelaiyuehao3 小时前
算法43,外观数列,模拟算法+双指针
java·算法