Skip to main content
Harish K
  1. Posts/
  2. DSA/

Visualize a Binary Tree in Python

·4 mins·

Yes, you read the title right! If you’re here, then I assume that you already have an understanding of the basic tree traversal methods (pre-order, post-order and in-order traversals). Using these methods, we can print all the nodes of a binary tree in a single line, or in multiple lines. In this post, we will see how we can use the binarytree package to visualize a binary tree.

thumb

Create a virtual environment (Optional)

This is an optional step. Virtual environments in Python keep project dependencies isolated, preventing conflicts between projects needing different libraries. This ensures your code runs the same way on any machine and makes collaboration easier by letting others easily set up the same environment.

To create a virtual environment, follow these steps:

  1. Create an empty folder that’ll serve as your project folder.
  2. Open the folder in Terminal (Mac/Linux) or Command Prompt (Windows)
  3. Now execute the below command:
python -m venv venv

This creates a folder that will store the virtual environment inside the project folder.

Now that the virtual environment is created, it has to be activated to run the Python interpreter from the virtual environment.

To activate the virtual environment, execute the below command:

If you’re on a Mac/Linux system:

source venv/bin/activate

If you’re on a Windows system:

venv\Scripts\activate.bat

Once the virtual environment is activated, you’ll see (venv) appended in the prompt line (see below image).

Untitled

To learn more about virtual environments, check this documentation.

Install the binarytree package

To display the binary tree in the terminal, we will utilize the binarytree package. To install the package, just execute the below command:

pip install binarytree

The package contains a class called Node. An instance of this class when printed, displays all its child nodes in the binary tree. Hence, when we print the root node, it displays the entire binary tree.

Create a module

You can avoid this step by including the code directly into the main python file. But creating a module helps with code reusability and avoid redundant lines of code. The module that we create, will have the function to display the binary tree. The function can be called from any python file inside the same project folder.

To create the module:

  1. Create a new file named “binarytree_helper.py”
  2. Now, paste the below lines of code into the file.
from binarytree import Node

class BT_Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def drawTree(v: BT_Node):
    if v == None:
        return None
    r = Node(v.data)
    r.left = drawTree(v.left)
    r.right = drawTree(v.right)
    return r

def printTree(v: BT_Node):
	print(drawTree(v))

Displaying the binary tree

Create another python file (say “sample.py”) in the same folder, and paste the below lines of code into the file.

from binarytree_helper import BT_Node, printTree

if __name__ == "__main__":
    root = BT_Node(1)
    root.left = BT_Node(2)
    root.right = BT_Node(3)
    root.left.left = BT_Node(4)
    root.left.right = BT_Node(5)
    root.right.left = BT_Node(6)
    root.right.right = BT_Node(7)
    root.left.left.left = BT_Node(8)
    root.left.left.right = BT_Node(9)
    root.left.right.left = BT_Node(10)
    root.left.right.right = BT_Node(11)
    root.right.left.left = BT_Node(12)
    root.right.left.right = BT_Node(13)
    root.right.right.left = BT_Node(14)
    root.right.right.right = BT_Node(15)

    printTree(root)

This python code constructs a binary tree using the BT_Node class and displays the tree structure using the printTree function imported from the binarytree_helper module.

Let’s see it in action. Run the python file by executing the below command:

python sample.py

Now, the tree is displayed in the terminal is a visually pleasing way with levels and branches.

Untitled

That’s it! We have done it!

beautiful-isnt-it-dr-kurt-boggs.gif

Let’s print some more trees.

Here’s a balanced tree:

from binarytree_helper import BT_Node, printTree

if __name__ == "__main__":

    root = BT_Node(10)
    root.left = BT_Node(20)
    root.right = BT_Node(30)
    root.left.left = BT_Node(40)
    root.left.right = BT_Node(50)

    printTree(root)

Untitled

And the below one is a skewed tree:

from binarytree_helper import BT_Node, printTree

if __name__ == "__main__":

    root = BT_Node(5)
    root.left = BT_Node(10)
    root.left.left = BT_Node(30)
    root.left.left.left = BT_Node(40)
    root.left.left.left.left = BT_Node(20)

    printTree(root)

Untitled

I can go on printing the different variations of the binary tree, but I think it’s good if I stop here. I hope you got the point. Now, this printTree() method can be called from any python file that you create in this project folder.

Alright! That’s how you visualise a binary tree in Python. I hope this post is helpful.

See you in an another one. Until then - stay safe, and keep coding!


Author
Author
Harish K
Eat. Code. Sleep. Repeat.