[英]No of Nodes in which nodes are smaller and greater than the certain node
給定一棵樹,請為每個頂點數大於其子樹中頂點的節點數和小於該頂點的節點數。
我可以通過進行深度優先搜索(DFS)來找到單個頂點的答案,但是對每個頂點進行搜索肯定會花費很多時間。
我們可以更快地解決該問題嗎?
更有效的方法:
一種更有效的方法是進行后期處理,並使用Binary Search Tree類型映射(可能在c ++中,排序的映射實現應該已經使用某種紅黑樹)來存儲鍵及其數量。
對樹進行后順序遍歷。 遍歷后的每個節點上:
a)對於更大的節點:
在BST類型圖中獲取當前節點的下一個最大值(這應該在O( log n )
完成,並對所有值進行計數(這將節省很多時間,尤其是在樹平衡的情況下),但是如果這樣做會很昂貴樹不平衡。
b)對於較小的節點:
獲取BST類型映射中當前節點的下一個最小值(此操作應在O( log n )
完成,並對其上方的所有值進行計數。
//map - sorted map with keys and their count
//greater_map - unordered map that contains node as key and count of nodes greater than key node.
//lesser_map - unordered map that contains node as key and count of nodes lesser than key node.
post_order( Node root )
if ( root == null ) return;
for each child in root.children:
post_order( child )
int next_higher_key = find_next_higher_key( map, root_key )
greater_map.insert(root, count_all_values_greater_than_equal_to(next_higher_key, map) )
int next_smaller_key = find_next_smaller_key( map, root_key )
lesser_map.insert(root, count_all_values_lesser_than_equal_to(next_smaller_key, map) )
if ( !map[root_key] )
map.insert( root_key, 1 )
else
map.insert( root_key, map[root_key] + 1 )
效率較低的方法:
進行一次深度優先遍歷樹一次。 遍歷完成后,在每個節點上,將較大節點和較小節點的數量存儲在兩個映射中。 鍵將是您剛剛完成遍歷的節點,值將分別是大於當前節點的節點數和小於當前節點的節點數。 從地圖中,您可以輕松獲得對於任何給定節點而言更大或更小的節點數量。
偽代碼:
list_of_nodes dfs( Node root ) {
list_of_nodes thisList = new list_of_nodes;
if ( root == null ) return thisList;
thisList.push( root );
for each child in root.children:
list_of_nodes childList = dfs( child )
thisList.addAll( childList )
int greater = 0, lesser = 0
for each node in thisList:
if node_value > root_value
greater++
else if node_value < root_value
lesser++
greatermap.insert( root, greater )
lessermap.insert( root, lesser )
return thisList
要獲得任何給定節點的更多,更少的節點數,您只需訪問地圖即可。
dfs( root_of_tree );
greater_num = greatermap[node]
lesser_num = lessermap[node]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.