Find the length of the longest path from root to a leaf node. Β β± Time
O(n)Β πΎ SpaceO(h)where h = tree height
Use post-order DFS (process children before parent). A leaf node returns 1. An internal node returns 1 + max(children heights). The root's return value is the total longest path.
Algorithm:
def longest_leaf(node):
if not node or no children: return 1
return 1 + max(longest_leaf(child) for child in node.children)
Tree:
A β depth 1
/ \
C Z β depth 2
| |
D X β depth 3
|
M β depth 4
Post-order computation:
longest_leaf(D) = 1 (leaf)
longest_leaf(C) = 1 + max(1) = 2
longest_leaf(M) = 1 (leaf)
longest_leaf(X) = 1 + max(1) = 2
longest_leaf(Z) = 1 + max(2) = 3
longest_leaf(A) = 1 + max(2, 3) = 4 β
Longest path: A β Z β X β M (length 4)
Tree height / depth is a foundational concept in computer science β the height of a balanced binary tree is O(log n), which determines the efficiency of BSTs, heaps, and B-trees. Post-order traversal for computing properties was systematised by Knuth in The Art of Computer Programming (1968).
- This is essentially tree height β same algorithm used in AVL trees to maintain balance
- For binary trees:
height(node) = 1 + max(height(left), height(right));Nonereturns 0 (or -1 for edges vs nodes) - Distinguish: depth of a node = distance from root; height of a node = distance to deepest leaf
- Diameter of a tree (LeetCode 543): at each node,
left_height + right_heightβ take global max
- Checking if a binary tree is balanced (|left_height - right_height| β€ 1 at every node)
- Evaluating time complexity of tree operations
- DOM tree depth analysis (browser rendering)
- File system depth traversal
- House Robber III β post-order tree DP
- DFS β the traversal used here
- N Leafs β counting leaf nodes