Ocaml 布局二叉搜索树
这就是65年的问题所在 给定二进制搜索和布局,如下所示:Ocaml 布局二叉搜索树,ocaml,Ocaml,这就是65年的问题所在 给定二进制搜索和布局,如下所示: 节点的y轴很简单,因为它只是级别编号,从1开始 节点的x asix稍微复杂一些,但是通过观察,假设整个树的高度是h,那么节点的x是左子节点的最大大小,就像它是一棵完整的树一样,即x=2^(h-y)-1 但是,有一种特殊情况,我们需要处理最左侧节点的x始终为1 这是我的密码: type 'a btree = Empty | Node of 'a * 'a btree * 'a btree type 'a pos_binary_tree
节点的y轴很简单,因为它只是级别编号,从1开始 节点的x asix稍微复杂一些,但是通过观察,假设整个树的高度是
h
,那么节点的x是左子节点的最大大小,就像它是一棵完整的树一样,即x=2^(h-y)-1
但是,有一种特殊情况,我们需要处理最左侧节点的x始终为1
这是我的密码:
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
type 'a pos_binary_tree =
| E (* represents the empty tree *)
| N of 'a * int * int * 'a pos_binary_tree * 'a pos_binary_tree
let rec height = function
| Empty -> 0
| Node (_,l,r) -> 1 + max (height l) (height r)
let get_fullsize h level = (2. ** (Float.of_int (h+1-level)) |> Int.of_float) - 1
let layout_btree2_correct t =
let h = height t in
let rec lay off y = function
| Empty -> get_fullsize h y, E
| Node (w, Empty, r) when off = 0 ->
let wtr, newr = lay 1 (y+1) r in
1+wtr, N (w, 1, y+1, E, newr)
| Node (w, l, r) ->
let wt1, newl = lay off (y+1) l in
let wt2, newr = lay (off+wt1+1) (y+1) r in
wt1+wt2+1, N (w, off+wt1+1, y, newl, newr)
in
lay 0 1 t |> snd
我所做的是:
以我的方式,我必须先在树上旅行一次才能得到高度。任何人都可以建议更好的实现,例如,只需遍历一次树?您是否要求使用不同的算法来搜索树?或者采用不同的方法来实现该算法 “树和树算法”部分可能对您有所帮助