農林漁牧網

您現在的位置是:首頁 > 林業

N叉樹的經典遞迴解決方案

2022-05-22由 逍遙埠 發表于 林業

遞迴樹怎麼構造

N叉樹的經典遞迴解決方案

樹的經典遞迴解決方案

類似於二叉樹的解決方案。

1、自頂向下的解決方案

2、自底向上的解決方案

自頂向下

自頂向下意味著在每次遞迴的級別,我們將首先訪問節點以獲得一些值,並在遞迴呼叫函式時將這些值傳遞給它的子節點。

一個典型的自頂向下遞迴函式 top_down(root,params)的邏輯過程:

1。 return specific value for null node

2。 update the answer if needed

3。 for each child node root。children[k]:

4。 ans[k] = top_down(root。children[k], new_params[k])

5。 return the answer if needed

N叉樹的經典遞迴解決方案

自底向上

“自下而上”是指在每個遞迴層中,我們首先遞迴地呼叫所有子節點的函式,然後根據返回值和根節點本身的值給出答案。

一個典型的自底向上遞迴函式bottom_up(root)的邏輯過程如下:

1。 return specific value for null node;

2。 for each child node root。children[k]:

3。 ans[k] = bottom_up(root。children[k])

4。 return answer

N叉樹的經典遞迴解決方案