Guest User

Untitled

a guest
Jun 24th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. module BinaryTree
  2.  
  3. // 节点类型
  4. type Node<'a> =
  5. {
  6. Value : 'a
  7. Left : Node<'a> option
  8. Right : Node<'a> option
  9. }
  10.  
  11. // 创建二叉树
  12. let myTree =
  13. {
  14. Value = 150
  15. Left =
  16. Some({
  17. Value = 30
  18. Left = None
  19. Right = Some({Value = 5;Left = None;Right = None})
  20. })
  21. Right =
  22. Some({
  23. Value = 45
  24. Left = Some({Value = 15;Left = None;Right = None})
  25. Right = None
  26. })
  27. }
  28.  
  29. // 先序遍历
  30. let rec IterPreorder (f : 'a -> unit) (root : Node<'a>) =
  31. f root.Value
  32. if root.Left.IsSome then
  33. IterPreorder f root.Left.Value
  34. if root.Right.IsSome then
  35. IterPreorder f root.Right.Value
  36.  
  37. // 对myTree执行先序遍历
  38. printfn "Preorder Iter:"
  39. myTree |> IterPreorder (fun x -> printfn "%A" x)
  40.  
  41. // 广度优先遍历
  42. let BFSIter (f : 'a -> unit) (root : Node<'a>) =
  43. let nextLayer (x : Node<'a> list) =
  44. x
  45. |> List.map (fun x -> [x.Left;x.Right])
  46. |> List.reduce (fun x y -> List.append x y)
  47. |> List.filter (fun x -> x.IsSome)
  48. |> List.map (fun x -> x.Value)
  49. let mutable iterQueue : Node<'a> list = [root]
  50. while not iterQueue.IsEmpty do
  51. List.iter (fun x -> f x.Value) iterQueue
  52. iterQueue <- nextLayer iterQueue
  53.  
  54. // 对myTree执行BFS遍历
  55. printfn "BFS Iter:"
  56. myTree |> BFSIter (fun x -> x |> printfn "%A")
  57.  
  58. // 求二叉树深度
  59. let rec Depth (root : Node<'a>) =
  60. 1 + max
  61. (match root.Left with
  62. |Some(x) -> Depth x
  63. |None -> 0)
  64. (match root.Right with
  65. |Some(x) -> Depth x
  66. |None -> 0)
  67.  
  68. // 求myTree深度
  69. myTree |> Depth |> printfn "Depth:%A"
Add Comment
Please, Sign In to add comment