首页 > 其他 > 详细

平衡二叉树

时间:2021-04-17 17:34:33      阅读:108      评论:0      收藏:0      [点我收藏+]

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

给定二叉树 [3,9,20,null,null,15,7]    3

   /   9  20
    /     15   7
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
  def height(root: TreeNode) -> int:
    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)

平衡二叉树

原文:https://www.cnblogs.com/wlhcode/p/14670492.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!