Implementing a binary tree
We will now create a binary tree (not a binary search tree). The key factor to have in a binary tree is that we must have two placeholders for the left child node and the right child node, along with the data we want to store in the node. A simple implementation of a binary node will look like this:
class BinaryNode { public $data; public $left; public $right; public function __construct(string $data = NULL) { $this->data = $data; $this->left = NULL; $this->right = NULL; } public function addChildren(BinaryNode $left, BinaryNode $right) { $this->left = $left; $this->right = $right; } }
The preceding code shows that we have a class with tree properties to store data, left and right. When we are constructing a new node, we are adding the node value to the data property, and left and right is kept NULL
as we are not sure if we need those or not. We also have an addChildren
method...