python logo

python tree


Python hosting: Host, run, and code Python in the cloud!

Introduction to Trees in Computer Science
In computer science, a tree is a unique data structure that draws inspiration from natural trees. Contrary to natural trees, this data structure tree stands inverted; with its root at the top. This tree comprises nodes, and the links connecting them are termed as edges. The nodes that don’t have any children are designated as leaf nodes. One crucial property of trees is the absence of cycles.

A tree with eight nodes. The root of the tree (5) is on top.

While Python is a versatile language, it doesn’t natively support trees.

Related Course:

Understanding Binary Trees
A binary tree is a special category of data structures. In this structure, every node is limited to a maximum of two children, specifically, a left and a right child. The tree’s root lies at the topmost position. Nodes situated beneath another node are termed as child nodes, while the node above them is their parent node. To represent this in Python, a class named ‘Tree’ is defined, possessing attributes for left and right nodes. Using this class, one can set up the tree’s root and define its left and right nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None

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

print(root.left.data)

For further expansion of the tree, you can add more nodes as illustrated below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None

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

root.left.left = Tree()
root.left.left.data = "left 2"
root.left.right = Tree()
root.left.right.data = "left-right"

← Previous | Next →






Leave a Reply:




Miguel Fri, 11 Mar 2016

Hello

Is there a way to dinamically assign the number of children branches for each parent branch?

Thanks!

Frank Sat, 12 Mar 2016

Hi Miguel!

Yes, it is possible to assign the number of children using a method, but if a tree has more than two children we can no longer call it binary.
I created some code:

#!/usr/bin/env python
class Tree(object):

def __init__(self):
self.left = None
self.child = []
self.data = []

def createChildren(self,amount):
for i in range(0,amount):
self.child.append(Tree())

def setChildrenValues(self,list):
for i in range(0,len(list)):
self.data.append(list[i])

root = Tree()
root.createChildren(3)
root.setChildrenValues([5,6,7])
root.child[0].createChildren(2)
root.child[0].setChildrenValues([1,2])
# print some values in the tree
print(root.data)
print(root.child[0].data[0])