Haskell:带列表的二叉搜索树

Haskell:带列表的二叉搜索树,haskell,binary-search-tree,Haskell,Binary Search Tree,我正在尝试构建一个二叉搜索树,但它没有按预期工作。例如,treeListInsert[7,12,6,4,8]给了我节点8(节点4 Nil(节点6 Nil(节点7 Nil)))(节点12 Nil Nil),这是错误的。我做错什么了吗?谢谢 -- the tree structure should be -- 7 -- / \ -- 6 12 -- / / -- 4 8 -- but results -- 8 -- / \

我正在尝试构建一个二叉搜索树,但它没有按预期工作。例如,
treeListInsert[7,12,6,4,8]
给了我
节点8(节点4 Nil(节点6 Nil(节点7 Nil)))(节点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
--树结构应为
--       7
--      / \
--     6   12
--    /   /
--   4   8
--但是结果
--       8
--      / \
--     4  12
--    / \
--   6   7
--定义数据结构
--在GHCI中导出“显示到显示”节点
数据树a=Nil |节点a(树a)(树a)派生显示
--| treeInsert接受任意数字和
--并返回一个节点
树插入::Ord a=>a->a树->a树
treeInsert x Nil=节点x Nil Nil--构建一个节点
树插入x(节点根左-右)
|x==根=节点根左-右-避免重复
|xroot=节点根左(treeInsert x right)--在右侧插入节点
--| treeListInsert获取数字列表
--并使用treeInsert函数返回树
treeListInsert::(Ord a)=>[a]->树a
treeListInsert[]=Nil--空列表返回Nil
treeListInsert(x:xs)=treeInsert x(treeListInsert xs)——迭代列表并重复将x插入到树中

插入函数很好,但是
treeListInsert
相当于
foldr treeInsert Nil
。基本情况是列表的结尾,而不是开始。你得到的树看起来是错误的(4作为左孩子有6个),但那是因为你画错了,而不是因为Haskell给了你一个坏结果。

感谢你指出
foldr
foldl
之间的区别。