Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breadth First Traversal for a Tree, Python

I figured out Depth First Traversal for a Tree.

def _dfs(tree, res):
    if tree:
        res += [tree.key]
        _dfs(tree.left, res)
        _dfs(tree.right, res)
    return res

I can't seem to find a solution for Breadth First Search. Will one have to use queues or stacks?

Thanks!!

like image 227
isal Avatar asked Dec 17 '22 01:12

isal


1 Answers

You can go with deques. This is a classic implementation of the bfs from Magnus Lie Hetland (using a FIFO queue).

from collections import deque

def bfs(G, s):
    P, Q = {s: None}, deque([s]) 
    while Q:
        u = Q.popleft() 
        for v in G[u]:
            if v in P: continue 
            P[v] = u 
            Q.append(v)
    return P
like image 152
luke14free Avatar answered Dec 18 '22 14:12

luke14free