深度嵌套哈希的DFS遍历



我在Ruby 中看到过这个问题递归遍历哈希

然而,我仍然无法做到这一点。有人能帮忙(也解释一下)吗。

输入散列:

{"." => {"foo" => {"hello" => {}, "world" => {}}, "bar" => {}}}

我只需要遍历它,而不搜索任何

如果所有值都是散列,这将起作用:

hash = {"." => {"foo" => {"hello" => {}, "world" => {}}, "bar" => {}}}
def traverse(hash, depth = 0)
  hash.each do |key, value|
    puts "#{depth} #{key}"
    traverse(value, depth + 1)
  end
end
traverse(hash)

输出:

0 .
1 foo
2 hello
2 world
1 bar

最新更新