Skip to content

Instantly share code, notes, and snippets.

@monorkin
Created September 29, 2018 22:51
Show Gist options
  • Save monorkin/9ac77bc10108dd9771de603688cfaa6a to your computer and use it in GitHub Desktop.
Save monorkin/9ac77bc10108dd9771de603688cfaa6a to your computer and use it in GitHub Desktop.
# return the array containing the tree levels, from root to last level.
def tree_by_levels(node)
return [] unless node
unpacked_tree = {}
breadth_first_search(node, unpacked_tree)
unpacked_tree.values.flatten
end
def breadth_first_search(node, hash = {}, depth = 0)
return unless node
hash[depth] ||= []
hash[depth] << node.value
breadth_first_search(node.left, hash, depth + 1)
breadth_first_search(node.right, hash, depth + 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment