如何找到下面给出的BST的最小值和最大值?
以下是我当前拥有的代码。不确定它是否正确,但是数据类型行必须保持不变。我正在尝试创建一个getmin和getmax功能。以下是对此的要求。
datatype tree = leaf | node of int * tree * tree;
fun isEmpty leaf = if leaf=nil then true else false;
fun inorder leaf = nil
| inorder (node(key,left,right)) = inorder left @ [key] @ inorder right;
fun preorder leaf = nil
| preorder (node(key,left,right)) = preorder left @ preorder right @ [key];
fun postorder leaf = nil
| postorder (node(key,left,right)) = [key] @ preorder right @ preorder left;
(* Inputs a BST. Returns the smallest value in the tree. If the tree is empty, the function should return NONE. *)
getMin : tree -> int option
(* Inputs a BST. Returns the largest value in the tree. If the tree is empty, the function should return NONE. *)
getMax : tree -> int option
对此的任何帮助将不胜感激。谢谢!
Below is the code I currently have. Not sure if it is even right, but the datatype line MUST remain the same. I am trying to create a getMin and getMax function. Below will be the requirements for it.
datatype tree = leaf | node of int * tree * tree;
fun isEmpty leaf = if leaf=nil then true else false;
fun inorder leaf = nil
| inorder (node(key,left,right)) = inorder left @ [key] @ inorder right;
fun preorder leaf = nil
| preorder (node(key,left,right)) = preorder left @ preorder right @ [key];
fun postorder leaf = nil
| postorder (node(key,left,right)) = [key] @ preorder right @ preorder left;
(* Inputs a BST. Returns the smallest value in the tree. If the tree is empty, the function should return NONE. *)
getMin : tree -> int option
(* Inputs a BST. Returns the largest value in the tree. If the tree is empty, the function should return NONE. *)
getMax : tree -> int option
Any help with this will be greatly appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过这个思考。
树
是leaf
或node
。 A节点
包含一个值和两个其他tree
s。叶
的最大值是多少?它没有值,因此是无
。节点
的最大值是多少?好吧,这是两个的最大值:您如何找到三个
int选项
值的最大值?一种方法可能是:Think this through. A
tree
is either aleaf
or anode
. Anode
contains a value and two othertree
s.What is the maximum value of a
leaf
? It doesn't have a value, so it'sNONE
.What's the maximum value of a
node
? Well, it's the maximum of either:How do you find the maximum value of three
int option
values? One way might be:更加惯用地,使用更精确的模式匹配,并遵循
int选项
规范,而不是使事物复杂化,而异常:More idiomatically, using more precise pattern matching, and following the
int option
specification instead of complicating things with exceptions: