# 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.

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!

--

--