【发布时间】:2014-03-27 12:24:45
【问题描述】:
我正在尝试实现一种算法(广度优先搜索或深度优先搜索)来遍历并从具有 UNKNOWN DEEP LEVEL 的二叉树(具有 2 个方向 WIN 或 LOSE)中提取数据(它可以向上至 80-90)。
我需要的是从根到叶子的每个节点的所有路径和内容。我试图找到一些方法来追踪路径,不仅是当前路径,而且是所有可能的路径。而且因为每当我们在一个叶子处完成时,我们需要从根重新开始,我们需要检查是否:
- 之前是否已经遍历过路径? (使用队列或堆栈????)
- 它停在哪里?所以我们可以从那里继续(使用标志检查???)
树:
所以我需要做的是找到从根 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。
#已编辑 我想使用 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
任何帮助将不胜感激!非常感谢!
【问题讨论】:
标签: python search binary-tree binary-search-tree