Trees
Trees in Computer Programming
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, child):
self.children.append(child)
def display_tree(node, level=0):
print(' ' * level * 2, node.data)
for child in node.children:
display_tree(child, level + 1)
# Example Usage:
root = TreeNode("Root")
child1 = TreeNode("Child1")
child2 = TreeNode("Child2")
root.add_child(child1)
root.add_child(child2)
child1.add_child(TreeNode("Grandchild1"))
child2.add_child(TreeNode("Grandchild2"))
display_tree(root)Different Types of Tree Data Structures in Computer Programming
Last updated
Was this helpful?