110. Balanced Binary Tree

Information

  • Diffculty: Easy

  • Created: 2020-01-09 23:28:25

  • Last Motified: 2020-01-09 23:28:25

  • Tags: Tree, Depth-first Search

Intuition

We could use DFS and compare height of left subtree and right subtree for each node.

Solution

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

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        self.balanced = True
        self._helper(root)
        return self.balanced

    def _helper(self, node):
        if node is None:
            return 0
        l = self._helper(node.left)
        r = self._helper(node.right)
        if abs(l - r) > 1:
            self.balanced = False
        return max(l, r) + 1