Performing Breadth First Search recursively

后端 未结 21 2530
不思量自难忘°
不思量自难忘° 2020-11-28 01:12

Let\'s say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?

Is it possible using only the call-stack

21条回答
  •  执念已碎
    2020-11-28 01:46

    The following seems pretty natural to me, using Haskell. Iterate recursively over levels of the tree (here I collect names into a big ordered string to show the path through the tree):

    data Node = Node {name :: String, children :: [Node]}
    aTree = Node "r" [Node "c1" [Node "gc1" [Node "ggc1" []], Node "gc2" []] , Node "c2" [Node "gc3" []], Node "c3" [] ]
    breadthFirstOrder x = levelRecurser [x]
        where levelRecurser level = if length level == 0
                                    then ""
                                    else concat [name node ++ " " | node <- level] ++ levelRecurser (concat [children node | node <- level])
    

提交回复
热议问题