假设我有以下形式的自定义树数据类型:
data BalTree a = Leaf | Node Integer (BalTree a) a (BalTree a) deriving (Eq, Show, Read)
并创建一个大小为 10 的新树,我会得到这个:
Node 10 (Node 5 (Node 2 (Node 1 Leaf 'Z' Leaf) 'Z' Leaf)
'Z'
(Node 2 (Node 1 Leaf 'Z' Leaf) 'Z' Leaf))
'Z'
(Node 4 (Node 2 (Node 1 Leaf 'Z' Leaf) 'Z' Leaf)
'Z'
(Node 1 Leaf 'Z' Leaf))
给定索引时,如何按顺序横向检索元素?
我的尝试:
ind Leaf pos = Nothing
ind tree@(Node n lt x rt) pos
| pos < 0 = Nothing
| pos > treeSize-1 = Nothing
| pos < hTreeSize = ind lt pos
| pos == hTreeSize = Just x
| pos > hTreeSize = ind rt (pos - hTreeSize)
where treeSize = size tree
hTreeSize = treeSize `div` 2
我不确定这是否是按顺序横向的并且它不会返回正确的结果。