Skip to content

Data Structures Part IV - Trees

Posted on:February 7, 2021 at 09:30 AM

What is a Tree?

Tree Class Definition in Python

class Tree:
    def __init__(self, data=None):
        self.left = None
        self.right = None
        self.data = data

Tree Implementation

# Recursive count node function
def count_all(node):
    return 1 + count_all(node.left) + count_all(node.right) if node else 0

# Implementing node class to form a tree
root = Tree()

root.data = 4
root.data = "root"

root.left = Tree()
root.left.data = "left"

root.right = Tree()
root.right.data = "right"

print(count_all(root))

Why use a Tree?