How can recursion be used to build and display a tree structure in PHP?
To build and display a tree structure using recursion in PHP, you can create a recursive function that traverses the tree nodes and prints them out in a hierarchical manner. Each node can have child nodes, which are also printed out recursively. This approach allows you to dynamically build and display tree structures of varying depths.
class Node {
public $value;
public $children = [];
public function __construct($value) {
$this->value = $value;
}
public function addChild(Node $node) {
$this->children[] = $node;
}
}
function displayTree(Node $node, $level = 0) {
echo str_repeat("-", $level) . $node->value . "\n";
foreach ($node->children as $child) {
displayTree($child, $level + 1);
}
}
// Build a tree structure
$root = new Node("Root");
$child1 = new Node("Child 1");
$child2 = new Node("Child 2");
$child3 = new Node("Child 3");
$root->addChild($child1);
$root->addChild($child2);
$child2->addChild($child3);
// Display the tree structure
displayTree($root);