gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:31:48 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com