[英]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.