Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created June 16, 2013 07:26
Show Gist options
  • Save ackintosh/5791267 to your computer and use it in GitHub Desktop.
Save ackintosh/5791267 to your computer and use it in GitHub Desktop.
DFS Algorithm in PHP
<?php
class Node
{
public $name;
public $children;
public function __construct($name)
{
$this->name = $name;
}
public function addChild(Node $child)
{
$this->children[] = $child;
}
}
/* Building Tree */
$root = new Node('root');
foreach (range(1, 6) as $v) {
$name = "child{$v}";
$$name = new Node($name);
}
$root->addChild($child1);
$root->addChild($child2);
$child1->addChild($child3);
$child1->addChild($child4);
$child2->addChild($child5);
$child2->addChild($child6);
/* Searching LeafNode */
function search_leaf(Node $node)
{
if (empty($node->children)) {
echo $node->name . ' is leaf !' . PHP_EOL;
return;
}
foreach ($node->children as $c) search_leaf($c);
}
search_leaf($root);
/*
* child3 is leaf !
* child4 is leaf !
* child5 is leaf !
* child6 is leaf !
*/
/* Searching Path to LeafNode */
function search_path_to_leaf(Node $node, $path)
{
if (empty($node->children)) {
echo "path : {$path}->{$node->name}" . PHP_EOL;
return;
}
foreach ($node->children as $c) search_path_to_leaf($c, $path . '->' . $node->name);
}
search_path_to_leaf($root, '');
/*
* path : ->root->child1->child3
* path : ->root->child1->child4
* path : ->root->child2->child5
* path : ->root->child2->child6
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment