Python: Binary Trees

 Hello and Welcome to blog #10, Python: Binary Trees. This post will introduce binary trees and how they work. It is recommended you read Python: Linked Lists first to understand certain things such as the concept of Nodes and how they link.


Binary Trees are very similar to Linked Lists in Python. However, where linked lists are formatted as one Node, or list element, after another, with each one linked to the next, Binary Trees are formatted like a tree. The element at the 'top' is called the root Node. After the root Node, every Node has a link left and right. The tree ends when absolutely none of the bottom Nodes have a link left or right. Here is an example: 

Binary Tree Data Structure - GeeksforGeeks


In this example, the Node at the top, 1, is the root Node. On the left is 2, and the right is 3. 2 is then linked to 4 and 5, and 3, 6 and 7. This same pattern continues until, where you can see the bottom row, none of the Nodes have a connection further down. The binary tree does not need to have these same values, each Node can have any value.


Also, as mentioned in the Linked Lists post, each Node has attributes, which you will have to define. These attributes include the Node's left link, right link, and it's 'val' or value. None of these attributes must be named this, it just depends on what you call it and how you use it. 


Other than Binary Trees, there are also BSTs, or Binary Search Trees, which are basically binary trees in which Nodes go in a certain place. For any given Node, the Node it is linked to left is lesser than that Node, and the Node that is greater than that Node is linked on its right. This basically leads to all the Nodes greater than the root on the right side in a specific order, and the same goes on the left with all the Nodes smaller than the root. 



Thank you for reading Python: Binary Trees. If you feel like you did not understand links and such, please look at Python: Linked Lists for more information. Please leave any comments or questions in the comments section!

Comments