algorithm - OCaml 中的二叉搜索树预排序算法

标签 algorithm ocaml binary-search-tree

我在 OCaml 中实现这个算法时遇到了问题,因为我必须在函数之间打印括号。

算法是这样的:

BEGIN
   WRITE ( "(" )
   IF (NOT EMPTY tree) THEN 
      IF (NOT EMPTY (left_leaf tree)) OR (NOT EMPTY (right_leaf tree)) THEN BEGIN
        WRITE (" ", root tree, " ")
        preorder (left_leaf tree)
        WRITE (" ")
        preorder (right_leaf tree)
      END ELSE
        WRITE (" ", root tree, " ")
   WRITE ( ")" ); {this has to be always executed}
END

这是我在 OCaml 中糟糕的尝试:

let rec preorderParenthesed tree = 

   print_string "(" in
   if not (isEmptyTree tree) then (
      if not (isEmptyTree(leftLeaf tree)) || not (isEmptyTree(rightLeaf tree)) then begin
        print_string " ";
        print_string (string_of_root (root tree));
        print_string " ";
        preorderParenthesed (leftLeaf tree);
        print_string " ";
        preorderParenthesed (rightLeaf tree);
      end else
        print_string " ";
        print_string (string_of_root (root tree));
        print_string " "; 
    ) 
    else if true then print_string ")\n";;

任何帮助将不胜感激

type bst = 
Empty   
| Node of (key * bst * bst);;

最佳答案

使用模式匹配可以使您的函数变得更加简单:

type 'a bst = Empty | Node of ('a * 'a bst * 'a bst)

let rec string_of_tree ~f = function
| Empty ->
  "()"
| Node (value, Empty, Empty) ->
  Printf.sprintf "(%s)" (f value)
| Node (value, left, right) ->
  Printf.sprintf "(%s %s %s)"
    (f value)
    (string_of_tree ~f left)
    (string_of_tree ~f right)

val string_of_tree : f:('a -> string) -> 'a bst -> string = <fun>

f is simply a string_of_* function.

模式描述了以下情况:

  1. 树是空的
    • ()
  2. 树不为空,但两个子树都是
    • (值)
  3. 树不为空,情况 2 未检查
    • (值 left_subtree right_subtree)

关于algorithm - OCaml 中的二叉搜索树预排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46276845/

相关文章:

python - 从非常大的列表中删除子列表的高效算法或python的内置函数

environment-variables - 如何检索所有可用的环境变量?

java - 将 BST 从使用 int 更改为使用字符串

java - 从数组中查找缺失的数字

algorithm - 编程难题 : How to paint a board?

Ubuntu Ocaml llvm 未绑定(bind)模块 ExecutionEngine

list - Ocaml 模式匹配

java - 在java中获取二叉搜索树的根

c++ - 插入方法未正确比较

javascript - Codility - 最小平均切片