Taylor's Blog

Atypical ramblings

The Tree Data Structure

I had mentioned briefly that Steve introduced me to the concept of a tree data structure. It’s a great structure due to its simplicity. You create a Node class that you attach to all of your data. All children of the node class then inherit a list and an append function to add to their list, allowing you to build your tree downwards. Here’s my simplified example:
[python]
class Node(object):
def __init__(self, data):
self.data = data
self.children = []

def add_child(self, obj):
self.children.append(obj)

apple = Node(‘Apple’)
banana = Node(‘Banana’)

fruits = Node(‘Fruits’)
fruits.add_child(apple)
fruits.add_child(banana)

broccoli = Node(‘Broccoli’)
carrot = Node(‘Carrot’)

vegetables = Node(‘Vegetables’)
vegetables.add_child(broccoli)
vegetables.add_child(carrot)

food = Node(‘Food’)
food.add_child(fruits)
food.add_child(vegetables)

for item in food.children:
print (item.data)

for item in fruits.children:
print (item.data)

for item in vegetables.children:
print (item.data)
[/python]

Updated: April 23, 2015 — 5:21 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Taylor's Blog © 2015