[leetcode] 110. Balanced Binary Tree @ python

原题

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 depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

3

/
9 20
/
15 7
Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

   1
  / \
 2   2
/ \

3 3
/
4 4
Return false.

解法1

递归, 定义depth函数计算节点的高度, 比较每个子树的高度差是否大于1, 如果是则返回False.
Worst case: O(n) + 1/2 * O(n/2) + 1/4 * O(n/4) + …

Time: O(n*log(n))
Space: O(1)

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        left_depth = self.depth(root.left)
        right_depth = self.depth(root.right)
        if abs(left_depth - right_depth) <= 1:
            return self.isBalanced(root.left)  and self.isBalanced(root.right)
        else:
            return False
        
    def depth(self, node):
        if not node:
            return 0
        return max(self.depth(node.left), self.depth(node.right)) + 1
        

解法2

一次遍历, 定义depth函数, 如果左子树或右子树的是不平衡的, 或者它们的高度差大于1, 则返回-1, 代表不平衡, 否则继续往下搜索. 最终我们检查depth的函数是否为-1
Time: O(n)
Space: O(1)

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def depth(root):
            # base case
            if not root: return 0
            left_depth = depth(root.left)
            right_depth = depth(root.right)
            if left_depth == -1 or right_depth == -1 or abs(left_depth- right_depth) > 1:
                return -1
            return max(left_depth, right_depth) + 1
        
        return depth(root) != -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值