簡體   English   中英

如何讀取 Haskell 中的二叉樹中的內容?

[英]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,最終我們會將39進行比較。 顯然9更大。 現在我們比較98 9又變大了。 然后919再次獲勝。

現在您只需將其翻譯成代碼

maxTree :: Tree -> Int
maxTree (Leaf n) = n
maxTree (Branch left right) = ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM