-
-
Save vestigegroup/519e731d1ca16c73646971b3c0209c82 to your computer and use it in GitHub Desktop.
PHP BFS on a Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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