简体   繁体   English

Haskell 中的二叉搜索树

[英]Binary Search Tree in Haskell

I am starting to learn Haskell and therefore I tried to implement a Binary Search Tree.我开始学习 Haskell,因此我尝试实现二叉搜索树。 My current code looks like this:我当前的代码如下所示:

data SearchTree = Empty | Node Int SearchTree SearchTree
  deriving Show


insert :: SearchTree -> Int -> SearchTree
insert Empty x = (Node x Empty Empty)
insert (Node n tl tr) x = if (x > n)
                       then insert tr x
                       else insert tl x

But somehow the second part of the insert function is not working correctly.但不知何故, insert功能的第二部分无法正常工作。 If I try these lines of code:如果我尝试这些代码行:

insert (Node 2 Empty Empty) 4

the result is Node 4 Empty Empty instead of a result like: Node 2 Empty (Node 4 Empty Empty) that I expected.结果是Node 4 Empty Empty而不是像我期望的那样的结果: Node 2 Empty (Node 4 Empty Empty)

Can someone tell me, what I did wrong?有人能告诉我,我做错了什么吗? Thanks :)谢谢 :)

When you recurse, you lose the information on the outer node.当您递归时,您会丢失有关外部节点的信息。 You have to re-wrap the result in a Node:您必须将结果重新包装在一个节点中:

data SearchTree = Empty | Node Int SearchTree SearchTree
  deriving Show


insert :: SearchTree -> Int -> SearchTree
insert Empty x = (Node x Empty Empty)
insert (Node n tl tr) x = if (x > n)
                       -- note the Node n tl (new_branch)
                       then Node n tl (insert tr x)
                       else Node n (insert tl x) tr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM