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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code