卖萌的弱渣

I am stupid, I am hungry.

Balanced Binary Tree

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.

Solution

(Balanced-Binary-Tree.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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):
    # should have two return value <balanced, height>
    # judge start from the bottom 
    def valid(self, node):
        if node == None:
            return True,0
        balanced, lh = self.valid(node.left)
        if balanced == False:
            return False,0
        balanced, rh = self.valid(node.right)
        if balanced == False:
            return False,0

        return abs(lh-rh)<=1, max(lh,rh)+1


    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        balanced, height = self.valid(root)
        return balanced