我创建了一个二叉搜索树:
data SearchTree a = Empty | Node a (SearchTree a) (SearchTree a) deriving (Show, Eq, Ord)
insertTreeElements :: (Ord a) => a -> SearchTree a -> SearchTree a --Create binary tree input method
insertTreeElements x Empty = Node x Empty Empty
insertTreeElements x (Node a left right)
| x == a = Node x left right
| x < a = Node a (insertTreeElements x left) right
| x > a = Node a left (insertTreeElements x right)
makeTree :: (Ord a) => (a -> SearchTree a -> SearchTree a) -> SearchTree a -> [a] -> SearchTree a --Create binary tree
makeTree iTE Empty li = foldr iTE Empty li
我正在尝试传递以下列表:
Type Age = Int
mylist = [Age 12, Age 100, Age 2, Age 3, Age 43]
但是输出不正确,它不会根据年龄的大小对树进行排序?如何编辑insertTreeElements以允许它与'Age x'一起使用?
答案 0 :(得分:1)
可能你遇到的最大问题是:
| x > a = Node a left (insertTreeElements x left)
请注意,您写了left
两次 - 大概其中一个应该是right
。