【发布时间】:2021-12-25 14:48:51
【问题描述】:
我有一棵二叉树:
data Btree a = Leaf a | Unary (Btree a) a | Binary (Btree a) a (Btree a) deriving Show
以及一些可以使用的示例:
ex1 = Binary (Binary (Leaf 0) 1 (Leaf 2)) 3 (Unary (Leaf 4) 5)
ex2 = Binary (Unary (Leaf 1) 2) 3 (Binary (Leaf 4) 5 (Leaf 10))
ex3 = Binary (Binary (Leaf (0,"a"))(1,"z")(Leaf (2,"x")))(3,"y")(Binary (Leaf (4,"b"))(5,"c")(Leaf (6,"d")))
我需要确定树是否完整,如果根与任何叶子之间的距离始终相同,直到 1,那么一棵树是完整的,所有最深的叶子都位于其他叶子的左侧,并且最多有一个内部节点应位于倒数第二级。
这是我目前所拥有的
complete :: Btree a -> Bool
complete x = fst $ go x where
go (Leaf _) = (True, 0)
go (Unary left _) = (leftTrue, 1 + leftCount) where
(leftTrue, leftCount) = go left
go (Binary left _ right) = (leftTrue && rightTrue &&
leftCount == rightCount,
1 + leftCount + rightCount) where
(leftTrue, leftCount) = go left
(rightTrue, rightCount) = go right
ex1 & ex3 应该返回 true,但只有 ex3 是。我相信一元部分是问题所在。
【问题讨论】:
-
根据定义,
Unary节点是一棵不完整的树,这意味着如果您看到它,您可以提前返回。那时不需要递归。 -
@chepner 我将如何实现它? go (Unary left _) = (True, 0) or (False, 0) 不起作用
-
抱歉,我把完全二叉树和完全二叉树混淆了。
-
(如果您正在寻找一个 full 二叉树,那么
go (Unary _ _) = (False, 0)可以工作,其中 0 可以是类型检查的任何值,因为您最终会忽略值。) -
请不破坏你的帖子。
标签: haskell binary-tree