Search code examples
rubydata-structurestreetraversaltree-traversal

BFS - TreeTraversal


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

Solution

  • 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 (e.g. "alice") and a left and right attribute, referring to the child nodes:

    Node = Struct.new(:name, :left, :right)
    

    To fill the nodes, we can use a helper 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]. We then print the row's names and create the follow-up row from the left and right child-nodes of our current row. We repeat until we run out of nodes, i.e. row becomes empty.

    Output:

    alice
    bob joseph
    tom richard elaine albert
    michelle amy colin liam