110. Balanced Binary Tree

Intuition

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

Solution

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

Information

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

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

  • Tags: Tree, Depth-first Search