To print each level of a tree on a separate line, you can use a level order traversal approach (or known as the breadth-first search (BFS) approach.) This involves traversing the tree level by level and printing the nodes at each level.

Step-by-Step Solution

  1. Build the Tree Structure: Create a hash to represent the tree structure, where each node points to its children.
  2. Perform BFS: Use a queue to perform a breadth-first search and print each level of the tree.

Example Code

Here is the code to achieve this:

tree = [
  { name: "fruit", parent: "root" },
  { name: "apple", parent: "fruit" },
  { name: "mac", parent: "apple" },
  { name: "cortland", parent: "apple" },
  { name: "grape", parent: "fruit" },
  { name: "red", parent: "grape" },
  { name: "white", parent: "grape" }
]

# Build the tree structure
tree_structure = Hash.new { |hash, key| hash[key] = [] }
tree.each do |node|
  tree_structure[node[:parent]] << node[:name]
end

# Perform BFS and print each level
def print_tree_levels(tree_structure, root)
  queue = [root]
  while !queue.empty?
    level_size = queue.size
    level_nodes = []
    level_size.times do
      node = queue.shift
      level_nodes << node
      queue.concat(tree_structure[node]) if tree_structure[node]
    end
    puts level_nodes.join(", ")
  end
end

# Print the tree levels starting from the root
print_tree_levels(tree_structure, "root")

Explanation

Output

The output will be:

fruit
apple, grape
mac, cortland, red, white

Summary

By following these steps, you can print each level of a tree on a separate line. If you encounter further issues or have additional questions, please provide more details about the context.