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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.