无队列的非递归广度优先遍历

Bas*_*ani 3 algorithm tree-traversal

在由具有指向父级、兄弟级和第一个/最后一个子级的指针的节点表示的通用树中,如下所示:

class Tnode {

    def data
    Tnode parent = null
    Tnode first_child = null, last_child = null 
    Tnode prev_sibling = null, next_sibling = null 

    Tnode(data=null) {
        this.data = data
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以在不使用任何其他辅助结构(例如队列)的情况下进行迭代(非递归)广度优先(级别顺序)遍历。

所以基本上:我们可以使用单节点引用进行回溯,但不能保存节点集合。到底能不能做到是理论上的部分,但更实际的问题是,在大段上不回溯的情况下,能否高效地做到。

ami*_*mit 5

是的你可以。但这很可能是一种权衡,并且会花费您更多的时间。

一般来说,一种方法是理解可以在树中实现没有额外内存的遍历。使用它,您可以执行Iterative Deepening DFS,它以 BFS 发现它们的相同顺序发现新节点。

这需要一些簿记,记住“你刚从哪里来”,并据此决定下一步做什么。

树的伪代码:

special_DFS(root, max_depth):
  if (max_depth == 0):
    yield root
    return
  current = root.first_child
  prev = root
  depth = 1
  while (current != null):
    if (depth == max_depth):
      yield current and his siblings
      prev = current
      current = current.paret
      depth = depth - 1
  else if ((prev == current.parent || prev == current.previous_sibling)
           && current.first_child != null):
    prev = current
    current = current.first_child
    depth = depth + 1
  // at this point, we know prev is a child of current
  else if (current.next_sibling != null):
    prev = current
    current = current.next_sibling
  // exhausted the parent's children
  else:
    prev = current
    current = current.parent
    depth = depth - 1
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下命令遍历您的级别顺序:

for (int i = 0; i < max_depth; i++):
   spcial_DFS(root, i)
Run Code Online (Sandbox Code Playgroud)