I have the following array of employees which I'm trying to traverse using BFS approach.
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. 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:
Exact Output Needed:
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