Post thumbnail
PYTHON

Creating a Binary Tree with the Largest Node as the Root: A Python Guide

By Suman Gangopadhyay

Binary trees are an essential data structure in computer science, providing an efficient way to store, manage, and retrieve data. In this guide, we’ll walk through creating a binary tree with the largest node in Python where the largest number from a given list is set as the root node. This tutorial blog will help you understand the process of recursive insertion and tree traversal with clear code and explanations.

Table of contents


  1. Objective
  2. Code Explanation
    • Step 1: Define the Node Class
    • Step 2: Define the SumanBinaryTree Class
  3. Recursive Insertion
  4. Printing the Tree
  5. Creating and Populating the Tree
  6. Output
    • Detailed Explanation of Output
  7. Conclusion
  8. Frequently Asked Questions
    • What is a binary tree, and why is it important?
    • Why is the largest number set as the root in this example?
    • What are the key properties of a binary search tree?
    • How can I print a binary tree structure?

Objective

Our objective is to create a binary tree from the list [252, 11, 15, 89, 987, 56, 43, 21, 98, 101, 136] with the largest number from the list as the root node.

Code Explanation

The code for the entire stuff is given as below. The description of it is as follows :- 

"""
Create a Binary tree from the list [252, 11, 15, 89, 987, 56, 43, 21, 98, 101, 136] with the largest number
from the list as its root node.
"""
class Node:    
    def __init__(self, val):
        self.val = val
        self.right = None
        self.left = None


class SumanBinaryTree:
    def __init__(self):
        self.root = None


    def insert_node(self, data):
        if self.root is None:
            self.root = Node(data)
        else:
            self.__insert__recursive(self.root, data)


    def __insert__recursive(self, node, data):
        if data < node.val:
            if node.left is None:
                node.left = Node(data)
            else:
                self.__insert__recursive(node.left, data)
        else:
            if node.right is None:
                node.right = Node(data)
            else:
                self.__insert__recursive(node.right, data)


    def print_tree(self, node, level=0):        
        if node is not None:
            self.print_tree(node.right, level + 1)
            print(' ' * 4 * level + '->', node.val)
            self.print_tree(node.left, level + 1)


# Create the binary tree
tree = SumanBinaryTree()
values = [252, 11, 15, 89, 987, 56, 43, 21, 98, 101, 136]


# Find the largest number and set it as the root
max_value = max(values)
tree.insert_node(max_value)


# Insert the remaining values
for value in values:
    if value != max_value:
        tree.insert_node(value)


# Print the tree
tree.print_tree(tree.root)

Step 1: Define the Node Class

The Node class represents a single node in the binary tree.

  • __init__ method: The constructor initializes a node with a value (val) and sets the left and right children to None.

Step 2: Define the SumanBinaryTree Class

The SumanBinaryTree class manages the binary tree and provides methods to insert nodes and print the tree.

  • __init__ method: Initializes the root of the tree to None.
  • insert_node method: Inserts a new node into the tree. If the tree is empty (root is None), it creates the root node. Otherwise, it calls the private method __insert__recursive to insert the node recursively.

Recursive Insertion

The __insert__recursive method handles the recursive insertion of nodes.

  • If the data is less than the current node’s value (node.val), it attempts to insert it into the left subtree. If the left child is None, it creates a new node there. Otherwise, it recurses into the left child.
  • Similarly, if the data is greater than or equal to the current node’s value, it follows the same logic for the right subtree.

Printing the Tree

The print_tree method prints the binary tree in a structured format.

  • It recursively prints the right subtree, current node, and left subtree, resulting in a visual representation of the tree.

Creating and Populating the Tree

Now, let’s create the binary tree and insert the specified nodes.

Find the largest number: We use the max function to find the largest number in the list, which is 987.

Set the largest number as the root: We insert 987 as the root node.

Insert the remaining values: We iterate through the list and insert the remaining values into the binary tree.

Output

Let’s examine the output of the print_tree method, which prints the tree structure.

output of Binary trees with the largest node
MDN

Detailed Explanation of Output

  • Root Node: 987 is the largest number and thus the root of the tree.
  • Second Level: 252 is less than 987 and becomes the left child of 987.
  • Third Level: Continuing to compare and insert values, 101 becomes the left child of 252 as it is less than 252 but greater than 11 and 15.

The tree is structured such that for any node, all values in its left subtree are less than the node’s value, and all values in its right subtree are greater than the node’s value.

Ready to master Python and unlock endless career opportunities in tech? GUVI’s Python Course is designed for learners of all levels, offering a comprehensive curriculum, hands-on projects, and expert mentorship. This course is designed to equip you with the knowledge and tools to excel in fields like AI, Data Science, and Web Development. Take the first step towards transforming your career with Python!

Conclusion

Creating a binary tree with the largest node as the root is an excellent way to learn about tree structures, recursive logic, and data organization in Python. The example demonstrated how to define node relationships, handle insertion, and visualize the tree’s structure effectively. By using the largest number as the root and recursively organizing the remaining nodes, we’ve built a binary tree that adheres to the fundamental properties of the structure. This guide serves as a practical foundation for more advanced applications, such as implementing search trees, balancing algorithms, and exploring binary heaps.

Frequently Asked Questions

1. What is a binary tree, and why is it important?

A binary tree is a hierarchical data structure where each node has at most two children (referred to as left and right). It is widely used for efficient searching, sorting, and hierarchical data representation.

2. Why is the largest number set as the root in this example?

Setting the largest number as the root demonstrates a specific approach to building a binary tree. It ensures that all smaller values are placed in the left subtree and equal or greater values in the right subtree, maintaining the binary search tree property.

3. What are the key properties of a binary search tree?

In a binary search tree (BST):
The left child contains values less than the parent node.
The right child contains values greater than or equal to the parent node.
This property allows for efficient searching, insertion, and deletion operations.

MDN

4. How can I print a binary tree structure?

The print_tree method used in the code recursively traverses the tree, printing the right subtree, the current node, and the left subtree. This approach gives a visually structured representation of the tree.

Career transition

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Power Packed Webinars
Free Webinar Icon
Power Packed Webinars
Subscribe now for FREE! 🔔
close
Webinar ad
Table of contents Table of contents
Table of contents Articles
Close button

  1. Objective
  2. Code Explanation
    • Step 1: Define the Node Class
    • Step 2: Define the SumanBinaryTree Class
  3. Recursive Insertion
  4. Printing the Tree
  5. Creating and Populating the Tree
  6. Output
    • Detailed Explanation of Output
  7. Conclusion
  8. Frequently Asked Questions
    • What is a binary tree, and why is it important?
    • Why is the largest number set as the root in this example?
    • What are the key properties of a binary search tree?
    • How can I print a binary tree structure?