PYTHON
Building a Generic Tree Structure with Custom Node Objects
Structure hierarchical data like file systems, UI components, or organizational charts in Python using a custom Node class for parent-child relationships.
class TreeNode:
def __init__(self, value, parent=None):
self.value = value
self.children = []
self.parent = parent
if parent:
parent.add_child(self)
def add_child(self, child_node):
self.children.append(child_node)
child_node.parent = self
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
def print_tree(self):
prefix = " " * self.get_level()
print(f"{prefix}|- {self.value}")
for child in self.children:
child.print_tree()
# Example Usage:
root = TreeNode("Global")
users = TreeNode("Users", root)
admin = TreeNode("Admin", users)
standard = TreeNode("Standard", users)
roles = TreeNode("Roles", root)
read_only = TreeNode("Read-Only", roles)
full_access = TreeNode("Full Access", roles)
root.print_tree()
# Output:
# |- Global
# |- Users
# |- Admin
# |- Standard
# |- Roles
# |- Read-Only
# |- Full Access
print(f"Level of 'Admin': {admin.get_level()}") # Output: Level of 'Admin': 2
How it works: This snippet illustrates how to create a generic tree data structure using a custom `TreeNode` class. Each node holds a `value`, a list of `children` (other `TreeNode` objects), and a reference to its `parent`. This design is fundamental for representing hierarchical data common in web development, such as folder structures, menu navigation, organization charts, or component trees in UI frameworks. The `print_tree` method demonstrates a simple way to visualize the hierarchy, and `get_level` helps determine the depth of any node within the tree.