Count Total Nodes in an N-ary Tree

Difficulty: EASYCategory: LLDFrequency: 1Asked On 2024-06-27

Problem Statement

Design and implement a system that represents an N-ary tree and provides functionality to count the total number of nodes in the tree.

Each node can have zero or more child nodes, and the tree is rooted (i.e., there is a single root node from which all other nodes descend).


🎯 Functional Requirements

Implement the following:

1. int countNodes(TreeNode root)

•Given the root of an N-ary tree, return the total number of nodes in the tree.
•Must work correctly for:
•An empty tree
•A tree with varying number of children at each node
•Deep trees (recursive or iterative implementation is acceptable)


🧱 Suggested Class Design

class TreeNode

1java 2CopyEdit 3class TreeNode { 4 int val; 5 List<TreeNode> children; 6 7 TreeNode(int val) { 8 this.val = val; 9 this.children = new ArrayList<>(); 10 } 11}


🧪 Example

1markdown 2CopyEdit 3 1 4 / | \ 5 2 3 4 6 / \ 7 5 6 8 9countNodes(root) → 6


🔐 Constraints

•0 ≤ number of nodes ≤ 10⁵
•Values of nodes are unique integers (if needed for debugging)
•Child order doesn't matter


✅ Evaluation Criteria

•Correct traversal of all nodes
•Recursive or iterative DFS/BFS is acceptable
•Avoid global/static counters unless encapsulated properly


✨ Optional Enhancements

•Count nodes of a specific depth
•Count leaf nodes only
•Add/Remove nodes dynamically and keep track of count efficiently


Solution

Comments