Balanced Binary Tree

Recursive Way

# ****************
# Descrption:
# 110. Balanced Binary Tree
# Given a binary tree, determine if it is height-balanced.
# ****************
class Solution(object):
        def isBalanced(self, root):
            def check(root):
                if root is None:
                    return 0
                left  = check(root.left)
                right = check(root.right)
                if left == -1 or right == -1 or abs(left - right) > 1:
                    return -1
                return 1 + max(left, right)

            return check(root) != -1

Iterative Way

class Solution(object):
    def isBalanced(self, root):
        stack, node, last, depths = [], root, None, {}
        while stack or node:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack[-1]
                if not node.right or last == node.right:
                    node = stack.pop()
                    left, right  = depths.get(node.left, 0), depths.get(node.right, 0)
                    if abs(left - right) > 1: return False
                    depths[node] = 1 + max(left, right)
                    last = node
                    node = None
                else:
                    node = node.right
        return True

results matching ""

    No results matching ""