代码随想录算法训练营第十五天-二叉树-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;
}
相关推荐
不穿格子的程序员21 分钟前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng1 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng1 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_800399721 小时前
stm32 printf重定向到USART
java·stm32·算法
顾安r2 小时前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L3 小时前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿3 小时前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
洛_尘3 小时前
数据结构--7:排序(Sort)
java·数据结构
元亓亓亓3 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495643 小时前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词