Implementing depth first search

The pseudocode for DFS looks straightforward. In order to track the sequence of node visits, we need to use a queue, which will track the nodes inside our Tree class. Here is our implementation of Tree class with recursive DFS:

class TreeNode {     public $data = NULL;     public $children = [];     public function __construct(string $data = NULL) {       $this->data = $data;     }     public function addChildren(TreeNode $node) {       $this->children[] = $node;     } } class Tree {     public $root = NULL;     public $visited;     public function __construct(TreeNode $node) {       $this->root = $node;       $this->visited = new SplQueue;     }     public function DFS(TreeNode $node) {       $this->visited->enqueue($node);       if($node->children){  foreach ($node->children ...

Get PHP 7 Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.