create a binary tree in php

To create a binary tree in PHP, we first need to define a class for the nodes. Each node will store a value and have pointers to its left and right children. Here's an example implementation:

main.php
class BinaryNode {
    public $value;
    public $leftChild;
    public $rightChild;

    public function __construct($value) {
        $this->value = $value;
        $this->leftChild = null;
        $this->rightChild = null;
    }
}
234 chars
12 lines

Now we can create a BinaryTree class that will serve as the entry point for our tree. This class will have a root node and methods for adding nodes to the tree.

main.php
class BinaryTree {
    public $root;

    public function __construct() {
        $this->root = null;
    }

    public function addNode($value) {
        $newNode = new BinaryNode($value);

        // If the tree is empty, the new node becomes the root.
        if ($this->root === null) {
            $this->root = $newNode;
            return;
        }

        // Otherwise, find the correct position for the new node.
        $current = $this->root;
        while (true) {
            if ($value < $current->value) {
                // If the value is less than the current node, move left.
                if ($current->leftChild === null) {
                    $current->leftChild = $newNode;
                    return;
                }
                $current = $current->leftChild;
            } else {
                // If the value is greater than or equal to the current node, move right.
                if ($current->rightChild === null) {
                    $current->rightChild = $newNode;
                    return;
                }
                $current = $current->rightChild;
            }
        }
    }
}
1139 chars
38 lines

To use the BinaryTree class, we can create a new instance and add nodes to it like this:

main.php
$tree = new BinaryTree();
$tree->addNode(5);
$tree->addNode(3);
$tree->addNode(7);
$tree->addNode(6);
$tree->addNode(4);
121 chars
7 lines

This will create a binary tree that looks like this:

main.php
    5
   / \
  3   7
     / \
    6   8
40 chars
6 lines

gistlibby LogSnag