fork download
  1. data Tree x = Leaf x
  2. | Node x [Tree x]
  3.  
  4. data TraversalResult x = TraversalResult Int [x]
  5.  
  6. dfs tree limit
  7. | limit == 0 = TraversalResult 0 []
  8. case tree of
  9. Leaf x -> TraversalResult 1 [x]
  10. Node x children ->
  11. let TraversalResult num_visited result = traverse children (limit - 1)
  12. in TraversalResult (num_visited + 1) result
  13.  
  14. traverse children limit
  15. | limit == 0 = TraversalResult 0 []
  16. case children of
  17. [] -> TraversalResult 0 []
  18. first : rest ->
  19. TraversalResult (visited_first + visited_rest) (result_first ++ result_rest)
  20. where TraversalResult visited_first result_first = dfs first limit
  21. TraversalResult visited_rest result_rest =
  22. traverse rest (limit - visited_first)
  23.  
  24. example_tree =
  25. Node 0 [
  26. Node 1 [Leaf 2, Leaf 3],
  27. Node 4 [Node 5 [Leaf 6]],
  28. Leaf 7
  29. ]
  30.  
  31. main = do
  32. (\limit -> let TraversalResult _ result = dfs example_tree limit in result)
  33. [1..8]
Success #stdin #stdout 0.02s 3548KB
stdin
Standard input is empty
stdout
[[],[],[2],[2,3],[2,3],[2,3],[2,3,6],[2,3,6,7]]