Skip to content

Instantly share code, notes, and snippets.

@lakhbawa
Last active November 13, 2021 08:32
Show Gist options
  • Save lakhbawa/0256e00bdef37003c5552a46fce0ac73 to your computer and use it in GitHub Desktop.
Save lakhbawa/0256e00bdef37003c5552a46fce0ac73 to your computer and use it in GitHub Desktop.
Binary Tree Data Structure Using PHP
<?php
// https://www.baeldung.com/java-binary-tree
class Node {
public $left, $right;
public $value;
public function __construct($value) {
$this->value = $value;
$this->left = null;
$this->right = null;
}
}
class BinaryTree {
public $root;
public function __construct() {
$this->root = null;
}
public function insert($value) {
if($this->root == null) {
$this->root = new Node($value);
} else if($value > $this->root->data) {
$this->root->left = $this->insert($value, $this->root->left);
} else if($value < $root->data) {
$this->root->right = $this->insert($value, $this->root->right);
}
}
public function addNode($value) {
$this->root = $this->addNodeRecursively($this->root, $value);
}
private function addNodeRecursively(?Node $current, int $value) {
if ($current == null) {
return new Node($value);
}
if ($value < $current->value) {
$current->left = $this->addNodeRecursively($current->left, $value);
} else if ($value > $current->value) {
$current->right = $this->addNodeRecursively($current->right, $value);
} else {
// value already exists
return $current;
}
return $current;
}
// perform an in-order traversal of the current node
public function traverseInOrder($root) {
if($root == NULL) {return; }
$this->traverseInOrder($root->left);
echo $root->value."\n";
$this->traverseInOrder($root->right);
}
}
$tree = new BinaryTree();
$tree->addNode(9);
$tree->addNode(6);
$tree->addNode(6);
$tree->traverseInOrder($tree->root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment