【问题标题】:Building a Tree in Haskell在 Haskell 中构建一棵树
【发布时间】:2014-11-01 02:41:03
【问题描述】:

我是 Haskell 的新手,我正在尝试构建一个包含整数的树,并且左子树中的每个元素都是

data Tree = Leaf | Node Int Tree Tree
    deriving (Eq, Show, Read, Ord)

insert :: Int -> Tree -> Tree
insert x (Tree n i t1 t2) = 

据我了解,我必须检查树的每个节点,看看它是否有一个 int,然后递归搜索子树。 请帮忙

谢谢

编辑:

我设法做了一些事情,但似乎无法创建新节点或者我检查错了,这是新代码:

data Tree = Leaf | Node Int Tree Tree
    deriving (Eq, Show, Read, Ord)

insert :: Int -> Tree -> Tree
insert x Leaf = Node x Leaf Leaf
insert x (Node i t1 t2)  
              | x <= i    = insert x t1
              | otherwise = insert x t2

为了检查,我写了:

let tree = insert 5 (insert 10 ( insert 11 ( insert 12 (insert 15 tree))))

但是当我在 ghci 中写的时候:

tree

我明白了:

Node 5 Leaf Leaf

【问题讨论】:

  • 我不明白如何检查是否有我正在寻找的节点
  • 我添加了一个编辑。请随时帮助我
  • 你的意思是Leaf,而不是let tree = ...右侧的tree吗?

标签: haskell


【解决方案1】:

当您 insert 进入节点时,您将返回 inserted 到 Node 的一侧,而不是新的 Node 数据 inserted 到一侧它。只有在Leaf 级别,您才会创建一个新节点。

insert :: Int -> Tree -> Tree
insert x Leaf = Node x Leaf Leaf
insert x (Node i t1 t2)  
          | x <= i    = Node i (insert x t1)  t2
          | otherwise = Node i  t1           (insert x t2)

【讨论】:

    【解决方案2】:

    Node 的递归案例的问题在于,尽管您调用 insert 在左侧或右侧创建一个新的子树,但之后您不会重建父树,您只需返回新的子树。

    例如,第一种情况应该是Node i (insert x t1) t2,第二种情况类似。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-29
      • 2020-02-05
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      相关资源
      最近更新 更多