Data Structures

How do you implement a binary tree in Python?

Medium
4
Added
A binary tree is a tree data structure in which each node has at most two children, referred to as the left child and the right child.

Solution Code

Data Structures
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

    def insert(self, key):
        if self.val is None:
            self.val = key
        elif key < self.val:
            if self.left is None:
                self.left = Node(key)
            else:
                self.left.insert(key)
        else:
            if self.right is None:
                self.right = Node(key)
            else:
                self.right.insert(key)

# Example usage
root = Node(10)
root.insert(6)
root.insert(14)
root.insert(3)
Explanation
This code snippet demonstrates how to implement a binary tree in Python.

Guided Hints

Define a Node class
Implement an insert method to add nodes
Use left and right pointers for child nodes