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;
}
相关推荐
All for pursuit.9 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
夏幻灵17 小时前
每日一题:LeetCode 3:无重复字符的最长子串——滑动窗口思路详解
算法·leetcode·职场和发展
无忧.芙桃17 小时前
C++ 并查集详解:原理、实现与应用
c语言·c++·算法·leetcode
蛋蛋的就会顺顺的17 小时前
hot100——二叉树
java·数据结构·算法·leetcode·力扣
Nil20820 小时前
leetcode 55跳跃游戏
算法·leetcode·游戏
longlongzihan20 小时前
LeetCode 128. 最长连续序列 —— 从排序到哈希集合
数据结构·c++·算法·leetcode·排序算法·哈希表
圣保罗的大教堂1 天前
leetcode 3302. 字典序最小的合法序列 中等
leetcode
Cccp.1231 天前
【leetcode】(九)哈希函数与哈希表
数据结构·leetcode·哈希算法
xieliyu.1 天前
LeetCode 1419 数青蛙:状态模拟求最少青蛙数量|Java 题解
java·算法·leetcode
Nil2081 天前
leetcode 45跳跃游戏Ⅱ
算法·leetcode·游戏