简体   繁体   English

"SML 二叉搜索树插入函数"

[英]SML Binary Search Tree Insert Function

I am new to SML and am trying to implement a BST.我是 SML 的新手,正在尝试实施 BST。 I have figured out how to parse through the tree, but am struggling with creating an insert function.我已经想出了如何解析树,但正在努力创建一个插入函数。 I want the function to be: insert(bst, key, value) of type BST * int * int -> BST where it inserts a key-value pair into a given tree and returns the resulting tree.我希望函数是:BST * int * int -> BST 类型的 insert(bst, key, value),它将键值对插入给定树并返回结果树。 I am struggling in the creation of this though, because I get a bit confused on making sure the function is of the right type.不过,我在创建它时很挣扎,因为我在确保函数的类型正确时有点困惑。

Here is my code so far, I have included an example tree as well到目前为止,这是我的代码,我还包含了一个示例树

(* left subtree, right subtree, key, value *)
datatype BST = Empty | Node of BST * BST * int * int;

fun parsePost [] = Empty
  | parsePost lst =
    let
      fun pP(stack, (0, k, v)::str) = pP(Node(Empty, Empty, k, v)::stack, str)
        | pP(L::stack, (1, k, v)::str) = pP(Node(L, Empty, k, v)::stack, str)
        | pP(R::stack, (2, k, v)::str) = pP(Node(Empty, R, k, v)::stack, str)
        | pP(R::L::stack, (3, k, v)::str) = pP(Node(L, R, k, v)::stack, str)
        | pP(T::stack, []) = T;
    in
      pP([], lst)
    end;

val exTree1 = [(0, 1, 1), (0, 3, 3), (3, 2, 2)];

If you insert a key and value pair into an empty tree, do you really expect to get an empty tree back?如果你将一个键值对插入到一棵空树中,你真的希望得到一棵空树吗? I very much doubt this is what you'd expect.我非常怀疑这是你所期望的。

Rather you'd probably expect a tree with that pair, but with empty branches.相反,您可能会期望一棵树有那对,但树枝是空的。

fun insert(Empty, x, y) = Node(Empty, Empty, x, y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM