如何迭代树PHP

时间:2018-11-20 16:15:21

标签: php recursion tree iteration

我有这样的结构。该结构有很多类别:

-Cat 1
   -subCat
-Cat 2
   -subCat
      -subcat
-Cat3

如何使用迭代和递归打印它们?另外,存储它们并添加和删除项目吗?

谢谢

1 个答案:

答案 0 :(得分:0)

这取决于您使用的是哪种树。您是在谈论二叉树,二叉搜索树还是“常规”树(有多个子级)。

对于二进制搜索树,您可以使用二进制搜索:

  public function search($value): ?BinarySearchNode {
        /** @var BinarySearchNode $node */
        $node = $this->getRoot();
        while (null !== $node) {
            if (Comparator::equals($value, $node->getValue())) {
                return $node;
            } else if (Comparator::lessThan($value, $node->getValue())) {
                $node = $node->getLeft();
            } else if (Comparator::greaterThan($value, $node->getValue())) {
                $node = $node->getRight();
            } else {
                throw new InvalidSearchComparisionException("no comparision returned true. Maybe you passed different data types (scalar, object)?");
            }
        }
        return null;
    }

还存在树遍历:预遍历,有序遍历和后遍历遍历。以下演示了预订:

  public function _traverse(?IBinaryNode $node) {
        if (null !== $node) {
            parent::visit($node->getValue());
            if (null !== $node->getLeft()) {
                $this->_traverse($node->getLeft());
            }
            if (null !== $node->getRight()) {
                $this->_traverse($node->getRight());
            }
        }
    }

通常,由于树是图形,因此可以使用DFS或BFS。以下是BFS的示例代码:

  public function searchByNode(?Node $node) {
        if (null === $node) return;
        $queue = new Queue();
        $this->visited->add($node);
        $queue->enqueue($node);
        while (!$queue->isEmpty()) {
            /** @var Node $n */
            $n = $queue->dequeue();
            $this->visit($n);
            /** @var Node $adjacent */
            foreach ($n->getAdjacents() as $adjacent) {
                if (!$this->visited->containsValue($adjacent)) {
                    $this->visited->add($adjacent);
                    $queue->enqueue($adjacent);
                }
            }
        }
    }

注意:示例来自库,请在此处查看:https://github.com/doganoo/PHPAlgorithms