Data Structures in Python: Tree

Till now we studied linear data structures in Python. Today, we will look at hierarchical data structure in Python i.e. Trees.

In the above figure, where do you think the root of the tree is? Obviously! to the bottom of the tree. But the tree data structure is upside down which means the root is at the top and leaves are to the bottom of the tree.

Representation of Tree

Each element of the tree is a node connected via edges. The root node is a level 0 node and the node which has no children/sub-category is a leaf node. In figure level-2 nodes are leaf nodes.

Let’s create a tree node in Python:

Above we created a Tree node where each node has data, children nodes, and a parent node(if it's not a root node)

Now let’s create a method to add a child to TreeNode

Now let’s create a method to print tree:

In the print_tree method, we used recursion until children are none.

Now let’s represent the family tree with this TreeNode:

Let’s print tree:

The output will look like this:

With our output, we can’t determine the level of nodes or which node is the root node and which node is children of which.

To print according to the level of every node we need to know the level of each node that’s why we will add one more method to get the level of each node and then use that method in the print_tree method to print according to levels.

Now, our output will be like this:

In the above output, we can see properly which node is at which level.

That’s all for today’s tutorial! Bye-bye!


Lecture 1:

Lecture 2:

Lecture 3:

Lecture 4:

Lecture 5:

Lecture 6:

Lecture 7:

Lecture 8:

Lecture 9:

Lecture 10:

Lecture 11:

Lecture 12:

Lecture 13:

Lecture 14:

Lecture 15:

Lecture 16:

Lecture 17:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store