Count Leaf Nodes - Problem

Given a binary tree, count the number of leaf nodes and internal nodes separately. Also, calculate the diameter of the tree (the longest path between any two nodes).

A leaf node is a node with no children. An internal node is a node with at least one child. The diameter is the number of edges in the longest path between any two nodes in the tree.

Return an array [leafCount, internalCount, diameter].

Input & Output

Example 1 — Basic Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [3,2,3]
💡 Note: Leaf nodes: 9, 15, 7 (count=3). Internal nodes: 3, 20 (count=2). Diameter: longest path 9→3→20→15 has 3 edges.
Example 2 — Single Node
$ Input: root = [1]
Output: [1,0,0]
💡 Note: Only root node exists: 1 leaf node, 0 internal nodes, diameter is 0 (no edges).
Example 3 — Linear Tree
$ Input: root = [1,2,null,3,null]
Output: [1,2,2]
💡 Note: Leaf: node 3. Internals: nodes 1, 2. Diameter: path 3→2→1 has 2 edges.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
INPUT TREE3920157Tree: [3,9,20,null,null,15,7]Blue: Internal nodesRed: Leaf nodesDFS ALGORITHM1Visit children first (post-order)2Classify node: leaf or internal3Count leaves and internals4Calculate diameter through nodeProcessing Results:Leaf count: 3 (nodes 9,15,7)Internal count: 2 (nodes 3,20)FINAL RESULT[3, 2, 3]Leaves: 3Internals: 2Diameter: 3Longest path:9 → 3 → 20 → 15(3 edges)Key Insight:Single DFS traversal processes child results bottom-up to calculate all threemetrics simultaneously: node classification, counting, and diameter calculation.TutorialsPoint - Count Leaf Nodes | Single DFS Approach
Asked in
Amazon 15 Microsoft 12 Google 8 Apple 6
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen