【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)
相关推荐
STLearner24 分钟前
SIGIR 2026 | LLM × Graph论文总结(图增强LLM,GraphRAG,Agent,多模态,知识图谱,搜索,推
人工智能·python·深度学习·神经网络·机器学习·数据挖掘·知识图谱
FreakStudio26 分钟前
MicroPython 内核开发者直接狂喜!这个 Claude 插件市场,把开发全流程做成了「对话式外挂」
python·单片机·嵌入式·面向对象·并行计算·电子diy
txzrxz30 分钟前
动态规划——背包问题
算法·动态规划
Yingye Zhu(HPXXZYY)34 分钟前
洛谷 P15553 [CCPC 2025 哈尔滨站] 液压机
算法
老陈说编程44 分钟前
12. LangChain 6大核心调用方法:invoke/stream/batch同步异步全解析,新手也能轻松学会
开发语言·人工智能·python·深度学习·机器学习·ai·langchain
给自己做减法1 小时前
rag混合检索
人工智能·python·rag
谭欣辰1 小时前
LCS(最长公共子序列)详解
开发语言·c++·算法
m0_629494731 小时前
LeetCode 热题 100-----17.缺失的第一个正数
数据结构·算法·leetcode
Cando学算法1 小时前
鸽笼原理(抽屉原理)
c++·算法·学习方法
Tisfy1 小时前
LeetCode 0796.旋转字符串:暴力模拟
算法·leetcode·题解·模拟·字符串匹配