[英]How do I read what's in a binary tree in Haskell?
我有以下類型:
data Tree = Branch (Tree) (Tree) | Leaf Int deriving(Show)
現在我想創建一個 function 給出樹中最高值的葉子。 但是我被卡住了,因為我不知道如何獲得給定樹的以下兩棵樹。
例如,我有一棵看起來像這樣的樹: let a = Branch (Leaf 10) (Leaf 2)
如何在另一個 function 中讀取值為10
的 Leaf?
典型的骨架如下所示:
maxTree :: Tree -> Int
maxTree (Branch x y) = {- TODO -}
maxTree (Leaf n) = {- TODO -}
在處理遞歸時,您需要牢記基本情況。
為了:
data Tree = Branch (Tree) (Tree) | Leaf Int deriving(Show)
您的基本情況是Leaf Int
。 葉子的最大值是……該葉子持有的值。
maxTree :: Tree -> Int
maxTree (Leaf n) = n
現在,您如何處理Branch
? 什么是Branch
? 它基本上是另外兩個Tree
。
考慮一個非常簡單的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
的最大值是通過計算出左右分支的最大值來計算的。 如果我們在每個Branch
上遞歸調用 maxTree,最終我們會將3
與9
進行比較。 顯然9
更大。 現在我們比較9
和8
。 9
又變大了。 然后9
比1
, 9
再次獲勝。
現在您只需將其翻譯成代碼。
maxTree :: Tree -> Int
maxTree (Leaf n) = n
maxTree (Branch left right) = ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.