你可以實現一個dfs遍歷爲每個節點生成一個散列值。將這些值與節點高度一起存儲在一個簡單的數組中。子樹候選項是重複值,只需檢查候選項是否正確,因爲兩個不同的子樹可以產生相同的散列值。
假設葉和內部節點都是類型節點和標準訪問和遍歷功能:
procedure dfs_update(node : Node, hashmap : Hashmap)
begin
if is_leaf(node) then
hashstring = concat("LEAF",'|',get_name_str(node),'|',get_type_str(node))
else // node is an internal node
hashstring = concat("NODE",'|',get_name_str(node))
for each child in get_children_sorted(node)
dfs_update(child,hashmap)
hashstring = concat(hashstring,'|',get_hash_string(hashmap,child))
end for
end if
// only a ref to node is added to the hashmap, we could also add
// the node's height, hashstring, whatever could be useful and inapropriate
// to keep in the Node ds
add(hashmap, hash(hashstring),node)
end
棘手的部分是dfs_update
之後,我們必須得到在collinding節點列表hasmap通過降低高度並檢查兩個兩個,他們確實是重複性的。
不錯,應該有效。我不是在回答這個問題,而是希望得到更多的想法。 –
你能舉一個這樣的散列函數的例子嗎?我傾向於這個哈希函數將很難實現。 – GeneralBecos
對於樹葉,我們可以使用任何散列值作爲字符串「LEAF | | 」和內部節點「NODE | | | | .... | 」。 –
Kwariz