在Ruby中,如何遍历父子关系中两个节点的哈希树

时间:2017-09-22 09:01:32

标签: ruby

假设你有这样的哈希:

{"a" => {
    "b" => {
        "d" => {}
    },
    "c" => {
        "e" => {},
        "f" => {
            "g" => {}
        }
    }
}

我想编写一个函数(使用递归),如果"a"是{{1}的直接后代,则为特定的一对键(例如"f""f")返回true }}。树中两者之间的深度或距离无关紧要。所有其他实例(例如"a""a"的后代,或"f""a"位于不同的分支上)应返回"f"

1 个答案:

答案 0 :(得分:2)

def are_descendants?(hash, node, target)
  node_hash = hash[node]

  # check
  # 1) the hash does actually have the node specified to be the start as a key 
  # 2) the target key is direct child => done 
  # 3) if not: check if any of the children is a parent of the target
  # 4) if the hash does not have the node specified to be the start, then look inside one of the hash's inner hashes
  (node_hash && 
    (node_hash.has_key?(target) || 
     node_hash.keys.any? { |key| are_descendants?(node_hash, key, target) })) ||
    hash.any? { |_, inner_hash| are_descendants?(inner_hash, node, target) })


end

are_descendants?(hash, "a", "f")
  => true

are_descendants?(hash, "f", "a")
  => false

are_descendants?(hash, "c", "f")
  => true