Tree Traversals: Breadth-First Search (BFS)
Tree Traversals: Breadth First Search (DFS)
The term traversal means to visit each node in a tree exactly once. In linear lists the order of traversal is vividly first to last. However, in trees there exists no such natural linear order.In this article, breadth first search is studied.
More Information About BFS:
- BFS can be defined as an algorithm dedicated to traversing a tree structure, level by level or depth by depth.
- This category of tree traversal initializes from the root node and explores all the adjacent nodes on a current level and then moves on to the next level, and so on.
Why Queue is better to traverse than Recursion?
- Queues improves the time complexity because recursion gives the time complexity of O(2^n) in the worst case, whereas queue gives time complexity of O(n).
- Height of the tree is first calculated to print level order but this is not required in queue.
- Implementation is shorter in queues.
- If the root is NULL, return.
- Otherwise push the root in queue.
- Print the node’s data and add its left and right child.
- Pop the node from the queue.
- Repeat until the queue is empty.
- Calculate height of tree.
- Initialize loop from 0 to height
- Recursive call for left and right subtree and decrease level by 1.
- If level is 0, print the nodes