- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Common Tree Problems
Trees
Common Tree Problems
Nearly every tree question is post-order: solve both subtrees, then combine. Once you see that, the code stops being something you memorise.
Depth and diameter
Two answers from one traversal
javascript
function maxDepth(node) {
if (!node) return 0
return 1 + Math.max(maxDepth(node.left), maxDepth(node.right))
}
// Longest path between any two nodes — it need not pass through the root.
function diameter(root) {
let best = 0
function depth(node) {
if (!node) return 0
const left = depth(node.left)
const right = depth(node.right)
// The best path through this node.
best = Math.max(best, left + right)
// What this node reports upward.
return 1 + Math.max(left, right)
}
depth(root)
return best
}