Leetcode110.平衡二叉树

Problem: 110. 平衡二叉树

思路

自顶向下递归:1. 对每个节点,分别计算左右子树的高度 2. 检查当前节点是否平衡(左右高度差 ≤ 1) 3.递归检查左右子树是否平衡

复杂度

  • 时间复杂度: O(n2)O(n^2) O(n2)(最坏情况(链表状树):第1层:遍历 n 个节点;第2层:遍历 n-1 个节点...总计:n + (n-1) + ... + 1 = O(n²))
  • 空间复杂度: O(n)O(n)O(n)(递归栈深度 = 树的高度,最坏情况(链表):O(n),平衡树:O(log n))

Code(C++)

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int height(TreeNode* root){
        if(root==NULL){
            return 0;
        }else{
            return max(height(root->left),height(root->right))+1;
        }
    }
    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }else{
            return abs(height(root->left)-height(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right);
        }
    }
};
相关推荐
Tim_109 分钟前
【LeetCode】338、比特位计数
c++·算法·leetcode
木子算法23 分钟前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
程序员AlbertTu1 小时前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算
Lazionr1 小时前
多态:从多种形态到运行时绑定
开发语言·c++
tryxr1 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
别动我齐刘海2 小时前
ROS2 Jazzy + C++ 实战路线——ros2_control
c++·人工智能·python·opencv·机器学习·机器人·github
Selvaggia2 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z2 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode