PHP code example of slince / tree-samples

1. Go to this page and download the library: Download slince/tree-samples library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

slince / tree-samples example snippets


class Node
{
    /**
     * @var int
     */
    protected $value;

    /**
     * @var Node
     */
    protected $left;

    /**
     * @var Node
     */
    protected $right;
    
    //...
}

$stack = new \SplStack();
$stack->push($node);

while (!$stack->isEmpty()) {
    $stack->top();
    $node = $stack->pop();
    $visitor($node); //此节点完成访问

    //压右子树
    if ($node->getRight()) {
        $stack->push($node->getRight());
    }
    if ($node->getLeft()) {
        $stack->push($node->getLeft());
    }
}

$queue = new \SplQueue();
$queue->enqueue($node);

while (!$stack->isEmpty()) {
    $node = $queue->dequeue();
    $visitor($node); //此节点完成访问
    //压左子树
    if ($node->getLeft()) {
       $queue->push($node->getLeft());
    }
    if ($node->getRight()) {
       $queue->push($node->getRight());
    }
}


// 创建三个节点的二叉树
$leftChild = new Slince\Tree\Node(2);
$rightChild = new Slince\Tree\Node(3);
$node = new Slince\Tree\Node(1, $leftChild, $rightChild);

// 使用宽度优先算法遍历
$bfs = new Slince\Tree\Traversal\BFS();
$numbers = [];
$bfs->travel($node, function(Node $node) use(&$numbers){
    $numbers[] = $node->getValue();
});

// 输出遍历顺序 
echo implode(',', $numbers);  // 1,2,3  

// 使用深度优先算法遍历
$dfs = new Slince\Tree\Traversal\DFS();
$numbers = [];
$bfs->travel($node, function(Node $node) use(&$numbers){
    $numbers[] = $node->getValue();
});

// 对于三个节点的二叉树,dfs和bfs的遍历顺序是一样的,有兴趣的可以自行尝试7个节点的二叉树遍历。