广度优先搜索遍历未知高度的二叉树

时间:2014-03-27 12:24:45

标签: python search binary-tree binary-search-tree

我尝试实现一种算法(广度优先搜索或深度优先搜索)来遍历并从二叉树中提取数据(使用2方向WIN或LOSE)具有未知深度级别(它可以高达80-90)。

我需要的是从根到叶子的每个节点的所有路径和内容。我试图找到一些方法来追踪路径,不仅是当前路径,还有所有可能的路径。因为每当我们完成一个叶子,我们需要从root开始,我们需要检查是否:

  • 路径是否已经遍历过? (使用队列或堆栈????)
  • 它停在哪里?所以我们可以从那里拿起并继续(使用标志来检查???)

树:

http://i59.tinypic.com/zkiznm.jpg

所以我需要做的是找到从根A到叶子的所有可能路径(V,Y,X,Q,Z,P,O,J,E,I,T,S,M)

所有可能的路径都是:

A -> C -> G -> L -> R -> V
A -> C -> G -> L -> R -> U -> Y
A -> C -> G -> L -> R -> U -> X
A -> C -> G -> L -> Q
A -> C -> G -> Z
A -> C -> F -> K -> P
A -> C -> F -> K -> O
A -> C -> F -> J
A -> B -> E
A -> B -> D -> I
A -> B -> D -> H -> N -> T
A -> B -> D -> H -> N -> S
A -> B -> D -> H -> M

每个节点都有我需要提取的数据。

当我们离开时,我们需要从头开始,但我们需要找到一些方法来跟踪我们遍历的路径,所以我们不必再这样做了树的高度不仅仅是这个例子的7级,它可能高达80-100。

#EDITED 我想使用BFS而不是DFS的原因是因为我想避免很快达到假期,因为我需要在此之后开始。如果它没有达到假期,那么获得尽可能多的数据来构建树将更容易。

我还在考虑这个算法,但我坚持了下来:

伪代码:

Create an empty tree
Create an empty queue to keep track of nodes that need to be processed.
Create an empty arrray of array (A) to save path. This array will be built up with each child     array is a possible path:
[ [WIN,WIN,WIN,WIN,WIN,LOSE,WIN,LOSE,LOSE,LOSE,LOSE],
  [WIN,WIN,WIN,WIN,WIN,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,LOSE,],
.............................................................................................
  [LOSE,LOSE,LOSE,LOSE,WIN,LOSE]]
Create an empty arrray of array (B) to save flag. This array will have exact size with A but it will have 2 value 0 when we haven't visit that node, 1 when we visit it). So this array will change value from 0 to 1 when we visit node.
[ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0,],
....................................................
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],

Add the starting point to the tree as the root node
Add the root node to a queue for processing

Repeat until the queue is empty (or finish):
  Remove a node from the queue 
  For child value WIN: 
    If the child hasn't already been processed: 
      Add it to the queue 
      Add it to array of array A
      Set 1 to array of array B
      Create an edge in the graph that connects the node and its neighbor

任何帮助都会很感激!非常感谢!

1 个答案:

答案 0 :(得分:0)

问题中有一些令人困惑的地方,如果你能回答它们,我可以给你算法。我们可以使用堆栈的哈希映射来解决这个问题,以存储所有访问过的路径。每当我们访问新节点时,我们将其添加到哈希并存储堆栈跟踪。现在这是一种非常低效的方法,另一种方法是使用父节点重建树。

如果您根本不了解算法。您可以从以下页面中获取灵感

http://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_2 http://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search

1)"我需要的是从根到叶子的每个节点的所有路径和内容。"
您希望查看到达叶子的所有路径或仅查找到点元素的所有路径。

2)"我试图找到一些方法来追踪路径,不仅是当前路径,还有所有可能的路径。"
对于每个节点,树中只有一个路径。

3)问题的其余部分让我假设你没有完全考虑过这个问题。如果您只是浏览了我给出的第一个wiki链接,您可以轻松地看到广度优先算法解决了一半的问题。