微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

给定一个类似“树”的数据结构,打印出从叶子到根的所有路径

如何解决给定一个类似“树”的数据结构,打印出从叶子到根的所有路径

有人可以指导我正确的方向吗,我不明白如何将结果从叶子返回到根

tree = {
    "name": "root","children": [
        {
            "name": "child1","children": [
                {
                    "name": "grand_child1","children": []
                },{
                    "name": "grand_child2","children": []
                }
            ]
        },{
            "name": "child2","children": []
        }
    ]
}

编辑: 解决方案应该是一种算法,因为如果树深度增加,它应该仍然有效

解决方法

您可以使用递归,例如:

def traverse(node,*names,&block)
  names.unshift(node[:name])

  yield *names and return if node[:children].empty?

  node[:children].each { |child| traverse(child,&block) }
end

该方法在单个节点上运行。在每次调用时,它将节点的名称添加到收集的 names 列表中(最初为空)。然后它为每个孩子再次调用自己,传递names。如果一个节点没有任何子节点,它会为给定的块产生 names。 (也被传递了)

用法:

traverse(tree) do |*names|
  p name: names
end

输出:

{:name=>["grand_child1","child1","root"]}
{:name=>["grand_child2","root"]}
{:name=>["child2","root"]}
,
def explore_tree(tree,names=[])
  names = [tree[:name]] + names
  if tree[:children].empty?
    p names
  else
    tree[:children].each { |child| explore_tree(child,names) }
  end
end
explore_tree(tree)

显示

["grand_child1","root"]
["grand_child2","root"]
["child2","root"]
,
def get_paths(hash)
  # Stop method and return name if name is address
  return hash[:name] if hash[:children].empty?
  paths = [] # Declaring path variable
  # Inspecting children
  hash[:children].each do |child|
    child_paths = get_paths(child)
    if child_paths.is_a? String
      paths << [child_paths,hash[:name]]
    else
      child_paths.each { |path| path << hash[:name] }
      paths += child_paths
    end
  end
  paths # Return paths
end

p *get_paths(tree).map { |path| path.to_s[1..-2] }
# => "grand_child1","child1,","root"
# => "grand_child2","root"
# => "child2","root"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。