代码随想录算法训练营第十五天-二叉树-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;
}
相关推荐
lally.2 分钟前
整数等差数列超图中的三个非微扰现象
算法
wabs66610 分钟前
关于字符串【力扣541.反转字符串II的思考】
数据结构·算法·leetcode·字符串
土司大王14 分钟前
LeetCode hot100——移动零
java·算法·leetcode
Tyler_TXZ1 小时前
C++C语言之——树
c语言·c++·算法·
旖旎夜光2 小时前
LeetCode 30:串联所有单词的子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
白狐_7982 小时前
408 数据结构|完全二叉树两道典型题:第 6 层叶结点数与叶结点总数
数据结构·算法
lucas_AI2 小时前
喂张白纸也能吐出证件号?文档 MLLM 的"关系级泄露"被测出来了
人工智能·算法·掘金技术征文
手写码匠2 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 灰度发布实战:让每一次变更都“小步快跑、随时可回滚“
人工智能·深度学习·算法·aigc
阿部多瑞 ABU2 小时前
从0到1:用 Spring Boot 3.4 + Vue3 做一个能“智能排道次“的运动会编排系统(附核心算法)
java·spring boot·后端·算法·spring
Nil2083 小时前
leetcode 48旋转图像
算法·leetcode·职场和发展