【leetcode】判断平衡二叉树

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

二叉搜索树(BST)

  • 性质:左子树所有节点值 < 根节点值 < 右子树所有节点值

  • 目的:快速查找(O(log n) 在平衡情况下)

  • 不保证平衡

平衡二叉树

  • 性质:每个节点左右子树高度差不超过1

  • 目的:避免树退化成链表,保持操作效率

  • 不保证有序性

python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        self.res = True
        def helper(root):
            if not root:
                return 0
            left = helper(root.left) + 1
            right = helper(root.right) + 1
            #print(right, left)
            if abs(right - left) > 1: 
                self.res = False
            return max(left, right)
        helper(root)
        return self.res
python 复制代码
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def height(root):
            if  not root:
                return 0
            return max(height(root.left),height(root.right))+1
        
        if not root:
            return True

        return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
相关推荐
无凭12 分钟前
字节跳动 DeerFlow:Agent Harness 怎么让大模型主动向用户提问?
人工智能·python
蜀道山老天师12 分钟前
Python + Playwright 实现问卷星自动化填写
python
Zane199423 分钟前
多开几个线程,为什么算数字反而没变快?一文讲透 CPython 的 GIL
后端·python
个 人 练 习 生24 分钟前
数据结构入门:算法复杂度
开发语言·数据结构·经验分享·学习·程序人生·算法
Ricardo-Yang29 分钟前
无人机单目深度估计测试:ZipDepth 与 AerialMetric
人工智能·算法·机器学习·计算机视觉·无人机
W_3260032 分钟前
Python-OpenCV边缘检测与阈值分割:Sobel、Scharr、Laplacian、Canny、全局与自适应阈值
开发语言·图像处理·python·opencv·机器学习
Nil20839 分钟前
golang解决单词转换
算法
imaol11 小时前
文件编程--标准IO
linux·运维·算法
青 春 记 忆1 小时前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
满怀冰雪1 小时前
21-图像分类实战:从 MNIST 到 CIFAR-10
人工智能·python·深度学习·分类·数据挖掘·paddlepaddle