如何从邮政订单构建二叉树

时间:2013-07-10 09:12:59

标签: algorithm f#

我从预订中找到了一个示例构建,如何从post构建二叉树 订单?

我编辑如下,是否正确

type BinaryTree = 
    | Nil 
    | Node of NodeType * BinaryTree * BinaryTree

let rec buildBSTfromPostOrder (l:NodeType list) = 
match l with
| [] -> Nil
| [a] -> Node(a, Nil, Nil)
| h::t -> 
    let b = Node(h, buildBSTfromPostOrder(t), buildBSTfromPostOrder(t))
    let smaller = 
               t 
               |> Seq.takeWhile (fun n -> n < h) 
               |> Seq.toList
    let bigger = 
               t 
               |> Seq.skipWhile (fun n -> n < h) 
               |> Seq.toList
    b


let input = [10; 1; 2; 2; 1; 50]

1 个答案:

答案 0 :(得分:1)

你不能,如果你想重建一些来自流(列表)的二叉树必须至少使用两个。

有一个Haskell版本(非常接近F#)

post [] _ = [] 
post (x:xs) ys = post (take q xs) (take q ys) ++         -- left
                 post (drop q xs) (drop (q + 1) ys) ++   -- right
                 [x]                                     -- node
    where (Just q) = elemIndex x ys 

该功能从前和后依次重建后期订单。可以适应其他版本。 (键也应该是唯一的)

如果您的树是订购的(BST),那么只需用键填充树。

要填充您的BST,您可以写

let rec insert tree n =
    match tree with
    | Nil -> Node(n, Nil, Nil)
    | Node(x, left, right) -> if n < x then Node(x, insert left n, right)
                                       else Node(x, left, insert right n)

let populate xs = Seq.fold insert Nil xs

例如

let rec show tree =
    match tree with
    | Nil -> printf ""
    | Node(x, left, right) -> do printf "[%d;" x
                                 show left
                                 printf ";"
                                 show right
                                 printf "]"

do show <| populate [|1;6;4;8;2;|]