Monday, July 16, 2012

PHP Code to create a BST and print it in Breadth First Order


/* take an array
 class node. take an element. traverse until the bst condition satisfies.

*/


class node
{
  public $value;
  public $left;
  public $right;
}

$input = array(5,7,3,4,2,6,9);

//  create a parent.

/*
  5
      3                  7
 2       4       6            9      

*/

$current = 0;

$parent = new node();
$parent->value = $input[$current++];
$parent->left = null;
$parent->right = null;

// take next element. see the bst condition.

$currentNode = $parent;

while( $current < count($input) )
{
// take the comparison here.
// move to the left or right accordingly.
// is it ready to insert  ?
if( $input[$current] >= $currentNode->value )
{
// currentNode needs to move to right.
// check if right is null.
if( $currentNode->right == null )
{
$currentNode->right
                        = createNewNode(& $input, & $current);
}
else
{
// advance current to its right.
$currentNode = $currentNode->right;
}
}
else if ( $input[$current] < $currentNode->value )
{

if( $currentNode->left == null )
{
$currentNode->left
                        = createNewNode(& $input, & $current);
}
else
{
// advance current to its left
$currentNode = $currentNode->left;
}
}
}

// Traverse the tree in BFT
// take the top, push all children. print current node.
// go to next level if all done with current level
// same logic almost.

$BFTQueue = array();

array_unshift($BFTQueue,  $parent);

echo "visit: ".$parent->value;

while( count($BFTQueue) > 0 )
{
// next level.
$BFTCurrent = array_pop($BFTQueue);

// print the value and push
echo "visit: ".$BFTCurrent->value;

if($BFTCurrent->left)
{
        array_unshift($BFTQueue, $BFTCurrent->left);
}
if($BFTCurrent->right)
{
        array_unshift($BFTQueue, $BFTCurrent->right);
}

}


function createNewNode($input, $current)
{
$newNode = new node();
$newNode->value = $input[$current++];
$newNode->left=null;
$newNode->right=null;

return $newNode;
}

No comments:

Post a Comment