haskell - 带有辅助函数的二叉搜索树谓词
问题描述
data BinaryTree a = Null | Node (BinaryTree a) a (BinaryTree a)
deriving Show
type BSTree a = BinaryTree a
treeBSMax :: (Ord a) => BSTree a -> a
treeBSMax btree = case btree of
Null -> error
Node _ val Null -> val
Node _ val right -> treeBSMax right
treeBSMin :: (Ord a) => BSTree a -> a
treeBSMin btree = case btree of
Null -> error
Node Null val _ -> val
Node left val _ -> treeBSMax left
isBSTree :: (Ord a) => BinaryTree a -> Bool
isBSTree btree = case btree of
Null -> False
Node Null val Null -> True
Node lt val rt -> val > treeBSMin lt && val < treeBSMax rt
如何使用treeBSMin
和treeBSMax
作为辅助函数isBSTree
来查找树是否是二叉搜索树?
解决方案
要将它们用作辅助函数,您需要首先使用以下方法从代码中删除部分Maybe
性:
treeBSMax :: (Ord a) => BSTree a -> Maybe a
treeBSMax btree = case btree of
Null -> Nothing
Node _ val Null -> Just val
Node _ val right -> treeBSMax right
treeBSMin :: (Ord a) => BSTree a -> Maybe a
treeBSMin btree = case btree of
Null -> Nothing
Node Null val _ -> Just val
Node left val _ -> treeBSMin left
isBSTree :: (Ord a) => BinaryTree a -> Bool
isBSTree btree = case btree of
Null -> True -- changed it!
Node Null val Null -> True
Node lt val rt -> isBSTree lt -- these two lines
&& isBSTree rt -- were missing !!
&& inOrder (treeBSMax lt) val (treeBSMin rt)
where
inOrder Nothing _ Nothing = True
inOrder Nothing v (Just y) = v <= y
inOrder (Just x) v Nothing = x <= v
inOrder (Just x) v (Just y) = x <= v && v <= y
这当然效率不高。(为什么留作练习)
推荐阅读
- c++ - C++ 中 extern "C" 与 extern "C" { } 的不同链接
- javascript - Firebase - 网络 - 在没有可用电子邮件的情况下验证帐户
- docker - .NET Core docker - Linux 容器。查找我的内置项目的特定文件
- java - 如何处理 Spring Data JDBC 中的软删除?
- java - java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Row
- javascript - 使用 bandintown API 搜索地理区域中的所有事件
- python - 如何检查同一个字典中是否存在两个键值对
- three.js - 使用 OrbitControls 围绕网格的 ThreeJS 奇怪的相机移动
- actions-on-google - 谷歌上的操作 - 如何处理长时间运行的操作
- python - Python:使用递归返回文件的完整路径