该函数应采用列表xs并构造一个平衡的二叉搜索树,其中包含与xs完全相同的元素集。
结果应该是这样的: (如果清单是[1,2,3,4,5,6,7,8])
节点(节点(节点(节点空1空)2空)4(节点空4空))5(节点(节点空6空)7(节点空8空))
也就是说树应该是这样的:
5
/ \
3 7
/ \ / \
2 4 6 8
/
1
而不是:
5
/ \
4 6
/ \
3 7
/ \
2 8
/
1
有人能告诉我怎么做吗?我发现我可以做第二棵不完美平衡的树,但不知道如何做第一棵树。
我感谢任何帮助!! 提前谢谢!
答案 0 :(得分:7)
对输入列表进行排序。现在创建一个树,其根节点是列表的中间元素,其左右子树是通过将此过程分别应用于中心左侧和右侧的子列表而生成的子树。
在Haskell:
buildBalanced [] = Empty
buildBalanced elts = Node (buildBalanced $ take half elts)
(elts !! half)
(buildBalanced $ drop (half+1) elts)
where half = length elts `quot` 2
main = putStrLn $ show $ buildBalanced [1,2,3,4,5,6,7,8]
-- prints Node (Node (Node (Node Empty 1 Empty) 2 Empty) 3 (Node Empty 4 Empty)) 5 (Node (Node Empty 6 Empty) 7 (Node Empty 8 Empty))
答案 1 :(得分:0)
如果树的顶部必须是中间元素:
mkBalanced [] = Empty
mkBalanced xs = Node mid (mkBalanced half0) (mkBalanced half1)
where (half0, half') = splitAt ((length xs `div` 2) - 1) xs
half1 = tail half'
mid = head half'
如果不是:
mkBalanced [] = Empty
mkBalanced (x:xs) = Node x (mkBalanced half0) (mkBalanced half1)
where (half0, half1) = splitAt (length xs `div` 2) xs