SML二进制搜索树

时间:2018-09-30 10:31:09

标签: recursion binary-search-tree sml

因此,对于SML中的二进制搜索树,我具有以下数据类型定义:

datatype tree = Void | Node of tree * int * tree;

我也有这个功能:

fun sub_tree a b Void = 
  | sub_tree a b (Node (t1, x, t2)) =
    if (a <= x) andalso (x < b) then
      Node ((sub_tree a b t1), x, (sub_tree a b t2))
    else
      sub_tree a b t2;

旨在穿过这棵树并产生另一棵树,其标签(函数中的x)大于或等于a且小于b(a <= x

现在我也有这个示例树:

val ex1 = Node(Node(Node(Void, 0, Node(Void, 2, Void)), 3, Node(Void, 5, Void)), 6, Node(Void, 7, Node(Void, 8, Node(Void, 9, Node(Node(Void, 10, Void), 12, Node(Void, 15, Node(Void, 19, Void)))))))

因此,该功能适用​​于以下情况:

sub_tree 5 8 ex1;
val it =  Node (Node (Void, 5, Void), 6, Node (Void, 7, Void)): tree

但是当a = 0&b = 1无效时,因为:

sub_tree 0 1 ex1;
val it = Void: tree

它应该返回:Node (Void, 0, Void)

因此,我需要一些帮助来指出我在函数中所犯的错误,谢谢!!

1 个答案:

答案 0 :(得分:1)

您需要确定sub_tree a b (Node (t1, x, t2))中的三种情况:

  • a <= x andalso x < b:包括子分支
  • x < a:检查右分支
  • b <= x:检查左子支行

因此,为了完成您的功能,请使用:

if (a <= x) andalso (x < b) then
  Node ((sub_tree a b t1), x, (sub_tree a b t2))
else if x < a then
  sub_tree a b t2;
else
  sub_tree a b t1;

可视化sub_tree a b (Node (t1, x, t2))的三种情况

       a, b <= x       |  a <= x andalso x < b  |       x < a, b
-----------------------+------------------------+----------------------
  x and t2 are to      |                        |  t1 and x are to
  the right of [a, b[  |  x lies within [a, b[  |  the left of [a, b[
  -> check t1          |  -> check t1 and t2    |  -> check t2