我有以下型別:
data Tree = Branch (Tree) (Tree) | Leaf Int deriving(Show)
現在我想創建一個函式來給出樹中最高值的葉子。但是我被卡住了,因為我不知道如何獲得給定樹的以下兩棵樹。
例如,我有一棵看起來像這樣的樹: let a = Branch (Leaf 10) (Leaf 2)
如何10在另一個函式中讀取具有值的 Leaf?
uj5u.com熱心網友回復:
典型的骨架如下所示:
maxTree :: Tree -> Int
maxTree (Branch x y) = {- TODO -}
maxTree (Leaf n) = {- TODO -}
uj5u.com熱心網友回復:
在處理遞回時,您需要牢記基本情況。
為了:
data Tree = Branch (Tree) (Tree) | Leaf Int deriving(Show)
您的基本情況是Leaf Int. 葉子的最大值是……該葉子持有的值。
maxTree :: Tree -> Int
maxTree (Leaf n) = n
現在,你如何處理一個Branch?什么是Branch? _ 它基本上是兩個Trees。
考慮一個非常簡單的Tree:
Branch
/ \
/ \
/ \
Leaf 1 Leaf 4
最大值顯然是4。為什么?因為maxTree右分支的maxTree計算量大于左分支的計算量。
考慮一個更復雜的Tree:
Branch
/ \
/ \
/ \
Leaf 1 Branch
/ \
/ \
/ \
Branch Leaf 8
/ \
/ \
/ \
Leaf 3 Leaf 9
答案很明顯9。我們怎么知道呢?好吧,maxTree告訴我們的最大值Leaf 1是1。每個Branch的最大值是通過計算左右分支的最大值來計算的。如果我們最終在每個上遞回呼叫 maxTree ,Branch我們將3與9. 顯然9更大。現在我們9比較8. 9又變大了。然后9到1, 并9再次獲勝。
現在您只需將其翻譯成代碼。
maxTree :: Tree -> Int
maxTree (Leaf n) = n
maxTree (Branch left right) = ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/423010.html
標籤:
