[英]BFS - TreeTraversal
I have the following array of employees which I'm trying to traverse using BFS approach.我有以下员工数组,我正尝试使用 BFS 方法遍历这些员工。
array = [
["alice", "bob", "joseph"],
["bob", "tom", "richard"],
["richard", "michelle", "amy"],
["joseph", "elaine", "albert"],
["albert", "colin", "liam"]
]
This array is unsorted but it represents a tree of Managers in a company.该数组未排序,但它表示公司中的经理树。 for each item in the array, index 0 is the manager while index 1 & 2 are the subordinates of the manager.
对于数组中的每个项目,索引 0 是经理,而索引 1 和 2 是经理的下属。 basically, it's a tree that looks like this:
基本上,它是一棵看起来像这样的树:
alice
/ \
bob joseph
/ \ / \
tom richard elaine albert
/ \ / \
michelle amy colin liam
Our output should match this exactly:我们的 output 应该完全匹配:
Exact Output Needed:确切的 Output 需要:
alice
bob joseph
tom richard elaine albert
michelle amy colin liam
I have tried this but it's showing only the nodes.我试过这个但它只显示节点。
array = [
["alice", "bob", "joseph"],
["bob", "tom", "richard"],
["richard", "michelle", "amy"],
["joseph", "elaine", "albert"],
["albert", "colin", "liam"]
]
new_array = Array.new
def treverse(array,new_array)
final_array = Array.new
arr = array.shift
i = true
arr.each do |b|
unless new_array.include?(b)
new_array.push(b)
end
array.each do |c|
if c.include?(b)
treverse(array, new_array)
end
end
end
return
end
treverse(array,new_array)
new_array.each do |p|
puts p
end
I'm not sure if you can do it solely on the given array.我不确定您是否可以仅在给定的数组上执行此操作。
I would start by turning the array into an actual tree structure.我将从将数组变成实际的树结构开始。 You could for example have a
Node
class with a name
(eg "alice"
) and a left
and right
attribute, referring to the child nodes:例如,您可以有一个
Node
class,它有一个name
(例如"alice"
)和一个left
和right
属性,指的是子节点:
Node = Struct.new(:name, :left, :right)
To fill the nodes, we can use a helper hash:要填充节点,我们可以使用助手 hash:
nodes = Hash.new { |h, k| h[k] = Node.new(k) }
array.each do |name, left, right|
nodes[name].left = nodes[left]
nodes[name].right = nodes[right]
end
root = nodes['alice']
#=> #<struct Node name="alice", left=#<struct Node name="bob" ...>, right=... >
Now, to traverse (and print) this tree in a breadth-first manner, we can use something like this:现在,要以广度优先的方式遍历(并打印)这棵树,我们可以使用如下代码:
def traverse(node)
row = [node]
until row.empty?
puts row.map(&:name).join(' ')
row = row.flat_map { |n| [n.left, n.right] }.compact
end
end
traverse(root)
The idea is to construct the topmost "row" which is simply our root node: [node]
.这个想法是构建最顶层的“行”,它只是我们的根节点:
[node]
。 We then print the row's names and create the follow-up row from the left
and right
child-nodes of our current row.然后我们打印行的名称并从当前行
right
left
节点创建后续行。 We repeat until we run out of nodes, ie row
becomes empty.我们重复直到用完节点,即
row
变空。
Output: Output:
alice
bob joseph
tom richard elaine albert
michelle amy colin liam
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.