algorithm - 使用堆栈遍历树时如何跟踪树的深度?

标签 algorithm tree

如果我有一个使用这样的堆栈的树遍历算法:

input: root
push root onto stack
while stack not empty:
    pop current node off stack
    mark current as visited
    for each of current node's successors:
        if successor not visited:
            push successor onto stack

有没有一种简单的方法可以修改这个算法以获得树的最大深度?如果我使用递归,我可以想到如何做到这一点,但我有点难以思考如何使用堆栈方法来做到这一点。

最佳答案

您可以将节点及其深度压入堆栈,然后跟踪迄今为止您所看到的最大深度。

input: root
push (root, 0) onto stack
max_depth = 0
while stack not empty:
    pop current (node, depth) off stack
    if depth > max_depth:
        max_depth = depth
    mark current as visited
    for each of current node's successors:
        if successor not visited:
            push (successor, depth+1) onto stack

return max_depth

关于algorithm - 使用堆栈遍历树时如何跟踪树的深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47467431/

相关文章:

javascript - 贪吃蛇游戏 : how to check if the head collides with its own body

java - 优化二维数组中的删除节点

arrays - 分割数组并找到最大值 |max (L) -max (R)|

php - 如何用PHP和MySQL创建JSON嵌套子父树(PDO方法)

node.js - 如何限制mongodb中父 Node 的最大引用

node.js - 创建 NPM 链接实用程序 - 从下到上跟踪依赖关系

algorithm - 在树中搜索具有特定属性的节点并分配树的属性的有效方法

javascript - 如何正确实现递归算法?

algorithm - 在树中查找路径的有效数据结构是什么?

python - 如何在 scikit-learn 中设置 ID3 算法?