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;
}
相关推荐
玖玥拾5 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
Hi李耶6 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
白白白小纯11 小时前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
zander25812 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
yyds_yyd_1008612 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue4721 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Re.不晚1 天前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
青山木1 天前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
星轨初途1 天前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode