如何在F#中创建具有唯一索引的二叉树

时间:2015-03-07 13:13:57

标签: f# binary-tree

如何编写递归函数来构建二叉树,其中叶子是(值,索引),索引是唯一的连续整数?

目前的代码如下:

let rec MakeTree size = 
    if size = 0 then 0 else
      match ran.Next (3) with
       | 0 -> Cow (MakeTree (size-1),MakeTree (size-1))
       | 1 -> Dog (MakeTree (size-1),MakeTree (size-1))
       | 2 -> Cat (MakeTree (size-1),MakeTree (size-1))

1 个答案:

答案 0 :(得分:0)

以下是没有值的版本,但很容易添加:

将树定义为:

type Tree<'T when 'T: comparison> = 
| Empty 
| Node of 'T * Tree<'T> * Tree<'T>

并制作类似

的插入函数
let rec insert index = function
| Empty -> Node(index, Empty, Empty)
| Node(i, left, right) when index < i -> Node(i, insert index left, right)
| Node(i, left, right) when index > i -> Node(i, left, insert index right)
| Node(i, left, right) when index = i -> Node(index, left, right)
| Node(_, _, _) as n -> n