• 力扣:110. 平衡二叉树(Python3)


    题目:

    给定一个二叉树,判断它是否是高度平衡的二叉树。

    本题中,一棵高度平衡二叉树定义为:

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

    来源:力扣(LeetCode
    链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

    示例:

    示例 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, 0],存在result中。

    如果当前结点只有左子树,记录[max(result[-1]) + 1, 0],替换result最后1个元素,替换的目的是保证result中最后2个元素中有至少1个是当前结点的子树。如果max(result[-1]) + 1已经大于1,说明此时左子树的深度大于等于2,而右子树的深度为0,所以返回False。

    如果当前结点只有右子树,同理只有左子树的情况。

    如果当前结点有左子树和右子树,记录[max(result[-2]) + 1, max(result[-1]) + 1],删除result中最后2个元素并添加新记录,这样操作的目的同样是保证result中最后2个元素中有至少1个是当前结点的子树。如果max(result[-2]) + 1和max(result[-1]) + 1相差大于1,说明此时已不满足平衡的条件,返回False。

    最后返回True,因为不平衡的情况会中途返回False,所以,如果没有中途返回说明是平衡二叉树。

    知识点:

    1.平衡二叉树:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过 1 。

    代码:

    1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, val=0, left=None, right=None):
    4. # self.val = val
    5. # self.left = left
    6. # self.right = right
    7. class Solution:
    8. def isBalanced(self, root: Optional[TreeNode]) -> bool:
    9. result = []
    10. stack = []
    11. while root or stack:
    12. while root:
    13. stack.append(root)
    14. root = root.left if root.left else root.right
    15. root = stack.pop()
    16. if root.left is None and root.right is None:
    17. result.append([0, 0])
    18. elif root.left and root.right is None:
    19. if (t1 := max(result[-1]) + 1) > 1:
    20. return False
    21. result[-1] = [t1, 0]
    22. elif root.left is None and root.right:
    23. if (t2 := max(result[-1]) + 1) > 1:
    24. return False
    25. result[-1] = [0, t2]
    26. else:
    27. if abs((t3 := max(result[-2]) + 1) - (t4 := max(result[-1]) + 1)) > 1:
    28. return False
    29. result.pop()
    30. result[-1] = [t3, t4]
    31. root = stack[-1].right if stack and stack[-1].left == root else None
    32. return True

  • 相关阅读:
    Shader实现呼吸效果
    为何手机5G有时候比4G还慢?
    IDEA的Maven换源
    java计算机毕业设计网上租房管理源码+系统+数据库+lw文档+mybatis+运行部署
    【C++】命名空间namespace,cin,cout,函数重载
    css 优惠券样式大全
    【MyBatis Plus】初识 MyBatis Plus,在 Spring Boot 项目中集成 MyBatis Plus,理解常用注解以及常见配置
    Python常见报错及解决方案,建议收藏
    八、鼎捷T100生产管理之委外管理篇
    Webview+AppbarLayout上下滑动冲突
  • 原文地址:https://blog.csdn.net/yunjieheng/article/details/133318512