4 of 7
Write a function max_depth(root) that returns the maximum depth (height) of a binary tree.
The depth is the number of nodes along the longest path from the root to a leaf node.
# 3 # / \ # 9 20 # / \ # 15 7 root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print(max_depth(root)) # 3
# 1 # \ # 2 root = TreeNode(1) root.right = TreeNode(2) print(max_depth(root)) # 2
print(max_depth(None)) # 0
| Complexity | |
|---|---|
| Time | O(n) β visit every node once |
| Space | O(h) β recursion stack, h = height |
root is None, return 01 + max(left_depth, right_depth)