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;
}
相关推荐
菜菜的顾清寒4 分钟前
力扣HOT100(48)图论-腐烂的橘子
算法·leetcode·图论
fengxin_rou19 分钟前
【滑动窗口与前缀和算法实战】:LeetCode560.438 高频题深度解析
java·算法·leetcode
Brilliantwxx39 分钟前
【算法从零到千】【1-7】 双指针算法
开发语言·c++·笔记·算法·leetcode·推荐算法
菜菜的顾清寒1 小时前
力扣HOT100(49)动态规划 -- 打家劫舍
算法·leetcode·动态规划
玖釉-1 小时前
LeetCode Hot 100 知识点总结与算法指南
c++·windows·算法·leetcode
进击的荆棘1 小时前
优选算法——队列+宽搜
数据结构·c++·算法·leetcode·bfs·队列
进击的荆棘1 小时前
优选算法——栈
数据结构·c++·算法·leetcode·
_日拱一卒14 小时前
LeetCode:207课程表
java·数据结构·算法·leetcode·职场和发展
风筝在晴天搁浅17 小时前
美团 LeetCode 692.前K个高频单词
算法·leetcode·职场和发展
z2005093018 小时前
今日算法(回溯子集)(模版题)
数据结构·算法·leetcode