haskell - Haskell:带列表的二叉搜索树
问题描述
我正在尝试构建一个二叉搜索树,但它没有按预期工作。例如,treeListInsert [7,12,6,4,8]
给我Node 8 (Node 4 Nil (Node 6 Nil (Node 7 Nil Nil))) (Node 12 Nil Nil)
,这是错误的。是不是我做错了什么?谢谢。
-- the tree structure should be
-- 7
-- / \
-- 6 12
-- / /
-- 4 8
-- but results
-- 8
-- / \
-- 4 12
-- / \
-- 6 7
-- define the data structure
-- deriving Show to show Node in GHCI
data Tree a = Nil | Node a (Tree a) (Tree a) deriving Show
-- | treeInsert takes any number and
-- and return a Node
treeInsert :: Ord a => a -> Tree a -> Tree a
treeInsert x Nil = Node x Nil Nil -- build a Node
treeInsert x (Node root left right)
| x == root = Node root left right -- avoid duplicate
| x < root = Node root (treeInsert x left) right -- insert a node on a left
| x > root = Node root left (treeInsert x right) -- insert a node on the right
-- | treeListInsert takes a list of numbers
-- and return a tree using treeInsert function
treeListInsert :: (Ord a) => [a] -> Tree a
treeListInsert [] = Nil -- empty list return Nil
treeListInsert (x:xs) = treeInsert x (treeListInsert xs) -- iterate through the list and insert x to tree repeatedly
解决方案
您的插入功能很好,但treeListInsert
相当于foldr treeInsert Nil
. 基本情况是列表的结尾,而不是开头。你得到的树看起来错了(4 有 6 个作为左孩子),但那是因为你画错了,而不是因为 Haskell 给了你一个糟糕的结果。
推荐阅读
- apache-spark - 如何在运行时动态地将依赖项添加到 spark executors
- http - httpcomponents-core:来自任何传入主机/ip的句柄
- sql - 存储过程中一列的两个可选参数
- c - 我的将给定输入存储在文本文件中的输入程序无法正常工作
- android - 如何在 xml android studio 中编辑按钮内的图像/图标的大小?
- python - 如何从视图中获取数据到模板 Django
- angular - 如何控制 ngx-plyr 上的自定义按钮
- nginx - 通过 certbot 更新 nginx 上的 ssl 证书
- gcc - 如何将此命令转换为 makefile 文件?
- sed - 找到一个具有前导空格的字符串并在下面添加行以添加行