Last active
September 12, 2024 09:20
-
-
Save chadyred/797afa1879d47e3117fd0d53018b8718 to your computer and use it in GitHub Desktop.
structural none linear data
This file contains hidden or 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
<?php | |
class TreeNode | |
{ | |
public function __construct(public readonly string $value, public readonly ?TreeNode $left = null, public readonly ?TreeNode $right = null) | |
{ | |
} | |
public function makeRightAsTreeNodeThenDo(TreeNode $right, callable $result): void | |
{ | |
$result(new self($this->value, $this->left, $right)); | |
} | |
} | |
class AggregateTreeNode | |
{ | |
public function __construct(public readonly TreeNode $root) | |
{ | |
} | |
} | |
// Structural non linear data | |
$root = new TreeNode('root'); | |
$node1 = new TreeNode('foo', $root); | |
$node2 = new TreeNode('bar', $node1); | |
$node1->makeRightAsTreeNodeThenDo($node2, function (TreeNode $res) use (&$node1) { | |
$node1 = $res; | |
}); | |
$root->makeRightAsTreeNodeThenDo($node1, function (TreeNode $res) use (&$root) { | |
$root = $res; | |
}); | |
$tree = new AggregateTreeNode($root); | |
$node = $tree->root; | |
// We always have the root tree node | |
do { | |
echo $node->value; | |
$node = $node->right; | |
} while($node); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment