Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find the root of a n-ary tree in Python
In an n-ary tree, each node can have multiple children. When given nodes of an n-ary tree in an array, we need to find the root node and reconstruct the tree. The root node is the only node that has no parent (in-degree = 0).
Algorithm
To find the root of an n-ary tree, we use the concept of in-degree:
Create an in-degree counter for all nodes
For each node, increment the in-degree of its children
The node with in-degree 0 is the root
Return the root node for tree reconstruction
Implementation
import collections
class Node:
def __init__(self, value, child=None):
self.val = value
self.children = []
if child is not None:
for node in child:
self.children.append(node)
def find_root(tree):
# Count in-degree for each node
indegree = collections.defaultdict(int)
# For each node, increment in-degree of its children
for node in tree:
for child in node.children:
indegree[child.val] += 1
# Find node with in-degree 0 (root)
for node in tree:
if indegree[node.val] == 0:
return node
return None
def preorder_traversal(node, result=None):
if result is None:
result = []
if node is None:
return result
# Visit current node
result.append(node.val)
# Visit all children
for child in node.children:
preorder_traversal(child, result)
return result
# Create the n-ary tree nodes
node6 = Node(65)
node5 = Node(56)
node4 = Node(42, [node5, node6])
node3 = Node(32)
node2 = Node(27)
node1 = Node(14, [node2, node3, node4])
# Array of all nodes (order doesn't matter)
tree = [node2, node1, node5, node3, node6, node4]
# Find root and display preorder traversal
root = find_root(tree)
print(preorder_traversal(root))
[14, 27, 32, 42, 56, 65]
Tree Structure
How It Works
The algorithm works by counting the in-degree (number of incoming edges) for each node:
Root node: Has in-degree 0 (no parent)
Child nodes: Have in-degree ? 1 (have parents)
Preorder traversal: Visit root first, then recursively visit children
Time Complexity
The time complexity is O(n) where n is the number of nodes, as we iterate through all nodes twice: once to count in-degrees and once to find the root.
Conclusion
Finding the root of an n-ary tree involves counting in-degrees to identify the node with no parent. This approach efficiently reconstructs the tree structure and enables preorder traversal from the root.
