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!!
Yes, you’ll have to use a queue to hold nodes which you’ve checked but have yet to recurse into.
Start with the root node in the queue, then repeat [pop a node and for each of its children, perform whatever action you need (
res += [tree.key]) and push it on the queue].