2017-09-22 1 views
-1

あなたは、このようなハッシュ考えてみましょう:私は(再帰を使って)関数を書きたい、どのように私は親子関係にある二つのノードのハッシュツリーをトラバースん

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

をtrueを返します"f""a"の直系子孫である場合、特定のキーのペア(たとえば"a""f")に対してツリー内の2つの間の深さまたは距離は重要ではありません。他のすべてのインスタンス("a""f"の子孫で、"a""f"は別のブランチにあります)はfalseを返します。

+1

_ "私は関数[...]を書いています" _ - あなたの特定の問題は何ですか? – Stefan

答えて

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 
+0

開始ノードをルートのキーの1つにしないように編集しました – ulferts

関連する問題