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;
}
相关推荐
琢磨先生David7 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝7 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll7 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐7 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶8 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER8 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了8 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333338 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录8 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1238 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode