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
- Build the Tree Structure: Create a hash to represent the tree structure, where each node points to its children.
- 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
- Build the Tree Structure: The
tree_structure
hash is built where each key is a parent node and the value is an array of its children. - Perform BFS: The
print_tree_levels
method performs a breadth-first search using a queue. It prints the nodes at each level by iterating through the queue and collecting the nodes at the current level.
Output
The output will be:
fruit
apple, grape
mac, cortland, red, white
Summary
- Build the Tree Structure: Create a hash to represent the tree structure.
- Perform BFS: Use a queue to perform a breadth-first search and print each level of the tree.
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.