【L​eetCode随手玩】Balanced Binary Tree (平衡二叉树) - 解题方式

110. Balanced Binary Tree (平衡二叉树)

大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄

题目描述

平衡二叉树 (balanced binary tree) 意思是树中每一個子树,它的左右子树的最大高度都不会相差大于1。现在,题目给一棵二叉树,编写一个函数来判断这树是否平衡二叉。

题目原文(英语)

按此进入题目链结

Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:
Given the following tree [3,9,20,null,null,15,7]
Return true.

    3    
    / \  
   9  20
     /  \    
    15   7

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]
Return false.

      1
     / \
    2   2
   / \
  3   3
 / \
4   4

解题方式

简单来说,首先我们要搞清楚每一棵子树是否都是平衡,才能够判断出主树是否平衡。因此,就写了一个计算任何子树深度的函数,再用递迴 (Recursion)的方法判断主树是否平衡,如果平衡则返回正数,反之 -1。
最后只需判別这个帮助函数是不是 -1 便可。

# 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: TreeNode) -> bool:
        return self.helper_countdist(root) != -1
    
    # Helping to count maximum depth of binary tree, return -1 is not balanced
    def helper_countdist(self, root: TreeNode):
        if not root:
            return 0
        
        left = self.helper_countdist(root.left)
        right = self.helper_countdist(root.right)
        if left == -1 or right == -1 or abs(left - right) > 1:
            return -1
        
        return 1 + max(left, right)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值