Balanced Binary Tree — LeetCode 110 Python Solution
EasyTreeDepth-First SearchBinary Tree
- Problem
- #110
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given a binary tree, determine if it is height-balanced.
Example
- Input
- root = [3,9,20,null,null,15,7]
- Output
- true
Python solution
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if root is None:
return 0
l, r = height(root.left), height(root.right)
if l == -1 or r == -1 or abs(l - r) > 1:
return -1
return 1 + max(l, r)
return height(root) >= 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 110. Balanced Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On study lists
This problem is on NeetCode 150 and Grind 75.
Frequently asked questions
- How hard is LeetCode 110. Balanced Binary Tree?
- LeetCode 110. Balanced Binary Tree is rated Easy on LeetCode.
- What is the time complexity of LeetCode 110. Balanced Binary Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 110. Balanced Binary Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 110. Balanced Binary Tree cover?
- LeetCode 110. Balanced Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.