繁体   English   中英

在二叉树中为每个节点找到最左边的叶子-已解决-在OCaml中遍历树-左边的叶子

[英]Find the farest leaf on the left for every node in binary tree - solved - tree traversal in OCaml - left leaves

我设法完成了这项任务。 答案如下。 也许有人会需要这种解决方案。

您在OCaml中有一棵二叉树。 每个节点都有一个int,左子节点,右子节点和对Node的引用。

type tree = Node of tree * int * tree * tree ref | Leaf;;

编写过程left_leaves : tree -> unit此过程必须在每个节点中将引用设置为其最深的左子节点。

         25
      /      \
     5        30
   /  \
  4    10
 /    /
2    6

对于每个节点,此过程都必须在该节点中设置引用,如下所示:

25 -> Node(Leaf, 2, Leaf, Leaf)
5 -> Node(Leaf, 2, Leaf, Leaf)
4 -> Node(Leaf, 2, Leaf, Leaf)
2 -> Leaf
10 -> Node(Leaf, 6, Leaf, Leaf)
6 -> Leaf
30 -> Leaf

如何在Ocaml中编写此程序? 我在考虑递归。 我们应该从树的底部走。 首先,我们应该更改对Leaf的引用。 然后,在下一步中,我们应该更改对左节点的引用,然后递归地将节点中的每个引用更改为其左子节点的引用。 我制作了添加用于构建BST树以进行测试的过程:

let rec add x tree =
match tree with
|Node (l, k, r, wsk) -> 
if x <= k then
Node (add x l, k, r, wsk)
else
Node(l, k, add x r, wsk)
|Leaf -> Node (Leaf, x, Leaf, ref Leaf)

let a = Node (Leaf, 25, Leaf, ref Leaf);;

let a = add 5 a;;

let a = add 10 a;;

let a = add 4 a;;

let a = add 2 a;;

let a = add 10 a;;

let a = add 30 a;;

let a = add 26 a;;

这是我的解决方案,但是不起作用。 我不知道为什么。

编辑:在这篇文章的版本中,我想出了怎么做。 我的代码:

let rec left_leaves tree =
match tree with
|Node (l, k, r, wsk) ->
(match l with
|Node (ll, lk, lr, lwsk) ->
left_leaves l; if ll = Leaf then wsk := l else wsk := !lwsk; left_leaves r;
|Leaf -> wsk := Leaf
)
|Leaf -> ();;

我的解决方案了。 在这篇文章的编辑过程中,我设法做到了。 ; d

暂无
暂无

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

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