Pattern visualizer
Diameter of Binary Tree
Every path has a unique highest node where it turns, and its length there is the depth of the left branch plus the depth of the right branch. One post-order pass computes each node's depth for its parent while recording the best turn seen anywhere — the longest path need not touch the root. Animated on: Return the diameter of the binary tree [1,2,3,4,5,null,null,6,null,null,7,8,null,null,9] — the number of edges on the longest path between any two nodes..
Post-order depth with a side-channel maximum
Call stack
Call depth(1) at the root. The diameter is the longest path between any two nodes; every path has one highest node where it turns, and its length there is left depth + right depth. So we recurse to the leaves first — no node can answer until its children have.
1best <- 02FUNCTION depth(node):3 IF node = null: RETURN 04 left <- depth(node.left)5 right <- depth(node.right)6 best <- MAX(best, left + right)7 RETURN 1 + MAX(left, right)8depth(root)9RETURN best
← / → step · space play · Home restart