<?php
class TreeNode
{
protected $data, $rightNode, $leftNode;
protected function __construct($data)
{
$this->data = $data;
$this->rightNode = NULL;
$this->leftNode = NULL;
}
}
class binTree extends TreeNode
{
private $root;
public function __construct()
{
$this->root = new TreeNode(NULL);
}
public function addNode($data)
{
if($this->root->data == NULL)
{
$this->root->data = $data;
}
else
{
if($data <= $this->root->data)
{
$this->addLeftNode($this->root->leftNode, $data);
}
else
{
$this->addRightNode($this->root->rightNode, $data);
}
}
}
private function addRightNode($node, $data)
{
if($node == NULL)
{
$node->rightNode = new TreeNode($data);
}
else
{
if($data <= $node->data)
{
$this->addLeftNode($node->leftNode, $data);
}
else
{
$this->addRightNode($node->rightNode, $data);
}
}
}
private function addLeftNode($node, $data)
{
if($node== NULL)
{
$node->leftNode = new TreeNode($data);
}
else
{
if($data <= $node->data)
{
$this->addLeftNode($node->leftNode, $data);
}
else
{
$this->addRightNode($node->rightNode, $data);
}
}
}
public function printTreeInOrder()
{
$this->print_inOrder($this->root);
}
public function printTreepreOrder()
{
$this->print_preOrder($this->root);
}
public function printTreePostOrder()
{
$this->print_postOrder($this->root);
}
private function print_postOrder($node)
{
if($node != NULL)
{
$this->print_postOrder($node->leftNode);
$this->print_postOrder($node->rightNode);
printf("%s, ", $node->data);
}
}
private function print_preOrder($node)
{
if($node != NULL)
{
printf("%s, ", $node->data);
$this->print_preOrder($node->leftNode);
$this->print_preOrder($node->rightNode);
}
}
private function print_inOrder($node)
{
if($node != NULL)
{
$this->print_inOrder($node->leftNode);
printf("%s, ", $node->data);
$this->print_inOrder($node->rightNode);
}
}
}
$tree = new binTree();
$tree->addNode('F');
$tree->addNode('B');
$tree->addNode('G');
$tree->addNode('A');
$tree->addNode('D');
$tree->addNode('I');
$tree->addNode('C');
$tree->addNode('E');
$tree->addNode('H');
echo "<br />In Order Traversal: ";
$tree->printTreeInOrder();
echo "<br />Pre-Order Traversal: ";
$tree->printTreePreOrder();
echo "<br /> Post-Order Traversal: ";
$tree->printTreePostOrder();
?>