【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)
相关推荐
深蓝电商API1 小时前
滑块验证码破解思路与常见绕过方法
爬虫·python
Ulyanov1 小时前
Pymunk物理引擎深度解析:从入门到实战的2D物理模拟全攻略
python·游戏开发·pygame·物理引擎·pymunk
颜酱2 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
sensen_kiss2 小时前
INT303 Coursework1 爬取影视网站数据(如何爬虫网站数据)
爬虫·python·学习
不知名XL2 小时前
day50 单调栈
数据结构·算法·leetcode
玄同7652 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
@––––––2 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
Yorlen_Zhang2 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
xsyaaaan2 小时前
代码随想录Day31动态规划:1049最后一块石头的重量II_494目标和_474一和零
算法·动态规划