天天看點

[勇者闖LeetCode] 110. Balanced Binary Tree

[勇者闖LeetCode] 110. Balanced Binary Tree

Description

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.

Information

  • Tags: Tree | Depth-first Search
  • Difficulty: Easy

Solution

利用DFS得到每個節點的高度,若節點的兩個子樹不平衡,則該節點的高度設為-1,最後通過二叉樹的高度是否大于等于0來決定二叉樹是否平衡。

Python Code
# 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
        """
        return (self.get_height(root) >= )

    def get_height(self, root):
        if root is None:
            return 
        left_h, right_h = self.get_height(root.left), self.get_height(root.right)
        if left_h <  or right_h <  or abs(left_h - right_h) > :
            return -
        return max(left_h, right_h) + ;