leetcode 110. 平衡二叉树 简单

给定一个二叉树,判断它是否是 平衡二叉树。

示例 1:

复制代码
输入:root = [3,9,20,null,null,15,7]
输出:true

示例 2:

复制代码
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false

示例 3:

复制代码
输入:root = []
输出:true

提示:

  • 树中的节点数在范围 [0, 5000]
  • -10^4 <= Node.val <= 10^4

分析:一棵树是平衡的,要么它是空树,要么它的左子树和右子树的高度之差的绝对值小于等于 1.用一个函数计算一个节点的子树高度,主函数内递归地判断所有的节点是否平衡。

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int height(struct TreeNode* node)
{
    if(node==NULL)return 1;
    return fmax(height(node->left),height(node->right))+1;
}
bool isBalanced(struct TreeNode* root) {
    if(root==NULL)return true;
    if(isBalanced(root->left)&&isBalanced(root->right)&&abs(height(root->right)-height(root->left))<=1)return true;
    return false;
}
相关推荐
想吃火锅10056 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
凌波粒6 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
退休倒计时6 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
小欣加油6 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒6 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode
凌波粒6 天前
LeetCode--46.全排列(回溯算法)
数据结构·算法·leetcode
吃着火锅x唱着歌6 天前
LeetCode 2530.执行K次操作后的最大分数
数据结构·算法·leetcode
sheeta19986 天前
LeetCode 每日一题笔记 日期:2026.06.16 题目:3612. 字符串特殊符号处理
笔记·算法·leetcode
CoderYanger6 天前
A.每日一题:2095. 删除链表的中间节点
java·数据结构·程序人生·leetcode·链表·面试·职场和发展
青山木6 天前
Hot 100 --- 矩阵置零
线性代数·算法·leetcode·矩阵·哈希算法