Binary Tree

How Binary Tree Works

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.

Key characteristics:

  • Each node has at most two children
  • There is no specific ordering between nodes
  • It can be used to represent hierarchical structures

In this visualization, nodes are added randomly to either the left or right child of an existing node. This is different from a Binary Search Tree, where the position of a new node is determined by its value.

class Node:
    value
    left
    right

class BinaryTree:
    root

    function insert(value):
        if root is null:
            root = new Node(value)
        else:
            insertRecursive(root, value)
        visualize()

    function insertRecursive(node, value):
        if node is null:
            return new Node(value)
        if random() < 0.5:
            node.left = insertRecursive(node.left, value)
        else:
            node.right = insertRecursive(node.right, value)
        return node