Count Nodes in an N-ary Tree
Difficulty: MEDIUMCategory: DSAFrequency: 1Asked On 2024-06-27
Problem Statement
Design a system to represent an N-ary tree, and implement a method to return the total number of nodes in the tree.
🎯 Functional Requirements:
1.Design appropriate classes and methods to represent an N-ary tree.
2.Implement a method countNodes() that returns the total number of nodes in the tree.
3.Support basic tree construction (inserting children).
⚙️ Non-Functional Requirements:
•The implementation should be object-oriented.
•The solution should work recursively or iteratively.
•The design should be clean and modular, allowing for future extensions (e.g., traversal, depth calculation).
🧱 Class Design:
1plaintext
2CopyEdit
3Class: Node
4- value: any
5- children: List<Node>
6
7Class: NAryTree
8- root: Node
9+ countNodes(): int
10+ addChild(parent: Node, child: Node): void🧠 Approach:
Use a Depth-First Search (DFS) traversal (recursive or stack-based) to count all nodes in the tree starting from the root.
✅ Example:
1python
2CopyEdit
3# Example N-ary Tree:
4# 1
5# / | \
6# 2 3 4
7# |
8# 5
9
10Total nodes: 5💻 Sample Implementation (Python):
1python
2CopyEdit
3class Node:
4 def __init__(self, value):
5 self.value = value
6 self.children = []
7
8class NAryTree:
9 def __init__(self, root=None):
10 self.root = root
11
12 def addChild(self, parent, child):
13 parent.children.append(child)
14
15 def countNodes(self):
16 def dfs(node):
17 if not node:
18 return 0
19 count = 1
20 for child in node.children:
21 count += dfs(child)
22 return count
23
24 return dfs(self.root)