Skip to content

Instantly share code, notes, and snippets.

@vestigegroup
Forked from KerryJones/bfs-tree.php
Created September 12, 2019 05:54
Show Gist options
  • Save vestigegroup/519e731d1ca16c73646971b3c0209c82 to your computer and use it in GitHub Desktop.
Save vestigegroup/519e731d1ca16c73646971b3c0209c82 to your computer and use it in GitHub Desktop.
PHP BFS on a Tree
function BFS( $node, $data ) {
if ( $node->data == $data )
return $node;
$node->visited = true;
$queue = new Queue;
$queue->enqueue($node);
while ( !$queue->isEmpty() ) {
$node = $queue->dequeue();
if ( !$node->visited ) {
if ( $node->data == $data )
return $node;
$node->visited = true;
}
if ( !is_null( $node->left ) )
$queue->enqueue( $node->left );
if ( !is_null( $node->right ) )
$queue->enqueue( $node->right );
}
}
class Queue {
protected $first;
protected $last;
public function enqueue($node) {
if ( is_null( $this->first ) ) {
$this->first = $this->last = $node;
} else {
$this->last->next = $node;
$this->last = $node;
}
}
public function dequeue() {
if ( is_null( $this->first ) )
return $this->first;
$node = $this->first;
$this->first = $node->next;
return $node;
}
public function isEmpty() {
return is_null( $this->first );
}
}
class Node {
public $data;
public $left;
public $right;
public $next;
public $visited = false;
public function __construct($data) {
$this->data = $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment