lowest common ancestor of a binary search tree in php

Php program for lowest common ancestor of a binary search tree. Here more solutions.
<?php
// Php program for
// Find the Lowest Common Ancestor (LCA)
// in a Binary Search Tree
// Tree Node
class TreeNode
{
public $data;
public $left;
public $right;
public function __construct($data)
{
$this->data = $data;
$this->left = NULL;
$this->right = NULL;
}
}
class BinarySearchTree
{
public $root;
public $status;
public function __construct()
{
$this->root = NULL;
$this->status = false;
}
// insert a element
public function addNode($data)
{
// Create a new node
$node = new TreeNode($data);
if ($this->root == NULL)
{
// When adds a first node in bst
$this->root = $node;
}
else
{
$find = $this->root;
// Add new node to proper position
while ($find != NULL)
{
if ($find->data >= $data)
{
if ($find->left == NULL)
{
// When left child empty
// So add new node here
$find->left = $node;
return;
}
else
{
// Otherwise
// Visit left sub-tree
$find = $find->left;
}
}
else
{
if ($find->right == NULL)
{
// When right child empty
// So add new node here
$find->right = $node;
return;
}
else
{
// Visit right sub-tree
$find = $find->right;
}
}
}
}
}
// Find LCA
public function findLCA($head, $x, $y)
{
if ($head != NULL && $this->status == false)
{
if ($head->data > $x && $head->data > $y)
{
$this->findLCA($head->left, $x, $y);
}
else if (($head->data < $x && $head->data < $y))
{
$this->findLCA($head->right, $x, $y);
}
else
{
echo "LCA (".strval($x).
",".strval($y).
") : ".strval($head->data), "\n";
$this->status = true;
}
}
}
// Setup to find the lowest lowest common ancestor
public function lca($x, $y)
{
if ($this->root == NULL)
{
//When BST are have no elements
echo "Empty Binary Search Tree\n";
}
else
{
$this->status = false;
// Assume that given x and y are exist in BST
$this->findLCA($this->root, $x, $y);
if ($this->status == false)
{
// When x and y are not exist in BST
echo "No LCA of node (".($x).",".($y).") \n";
}
}
}
public static function main()
{
$tree = new BinarySearchTree();
/*
7
/ \
/ \
4 10
/ \ / \
3 6 8 11
/ \
5 9
*/
$tree->addNode(7);
$tree->addNode(4);
$tree->addNode(3);
$tree->addNode(6);
$tree->addNode(10);
$tree->addNode(8);
$tree->addNode(11);
$tree->addNode(9);
$tree->addNode(5);
// Test Case A
$tree->lca(5, 9);
// Test Case B
$tree->lca(9, 11);
// Test Case C
$tree->lca(3, 4);
}
}
BinarySearchTree::main();
Output
LCA (5,9) : 7
LCA (9,11) : 10
LCA (3,4) : 4
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment