DEV Community

SAMUEL ADENIJI
SAMUEL ADENIJI

Posted on

how to create a binary treenode with python

class BinaryTreeNode:
def init(self, data):
self.data = data
self.left_child = None
self.right_child = None

def insert(self, new_value):
    """Insert a new node with the given value into the BST."""
    if new_value < self.data:
        if self.left_child is None:
            self.left_child = BinaryTreeNode(new_value)
            print(f"Inserted {new_value} to the left of {self.data}")
        else:
            self.left_child.insert(new_value)
    elif new_value > self.data:
        if self.right_child is None:
            self.right_child = BinaryTreeNode(new_value)
            print(f"Inserted {new_value} to the right of {self.data}")
        else:
            self.right_child.insert(new_value)
    else:
        # Duplicate value found; not inserted
        print(f"Value {new_value} already exists in the tree.")

def search(self, key):
    """Search for a node with the specified key in the BST."""
    if self.data == key:
        print(f"Found {key}")
        return True
    elif key < self.data:
        if self.left_child is not None:
            return self.left_child.search(key)
        else:
            print(f"{key} not found in the tree.")
            return False
    else:  # key > self.data
        if self.right_child is not None:
            return self.right_child.search(key)
        else:
            print(f"{key} not found in the tree.")
            return False
Enter fullscreen mode Exit fullscreen mode

Example usage

if name == "main":
root = BinaryTreeNode(15)
root.insert(10)
root.insert(25)
root.insert(6)
root.insert(14)
root.insert(20)
root.insert(60)

# Searching for nodes
root.search(14)  # Should find the node
root.search(99)  # Should report that the node is not found
root.search(6)
root.search(88)
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️