Sunday, February 28, 2021

Tree BFS in JS (Queue/Array)

Tree properties

1. The maximum number of nodes at level ‘l’ of a binary tree is 2^l
2. The Maximum number of nodes in a binary tree of height ‘h’ is 2^h – 1, Height of a tree with a single node is considered as 1.

BFS Complexity
Time Complexity - O(n)
Space Complexity - O(n)

Notes: BFS slower than DFS

From geeksforgeeks: 

Extra space required for Level order traversal is likely to be more when tree is more balanced and extra space for Depth First Traversal is likely to be more when tree is less balanced.

How to Pick One?

  1. Extra Space can be one factor (Explained above)
  2. Depth First Traversals are typically recursive and recursive code requires function call overheads.
  3. The most important points is, BFS starts visiting nodes from root while DFS starts visiting nodes from leaves. So if our problem is to search something that is more likely to closer to root, we would prefer BFS. And if the target node is close to a leaf, we would prefer DFS.

Exercise:
Which traversal should be used to print leaves of Binary Tree and why? DFS
Which traversal should be used to print nodes at k’th level where k is much less than total number of levels? BFS

See the Pen Tree BFS in JS (Recursive & Non-recursive Queue versions) by Dhiviya Dhanasekar (@dhiviyadhanasekar) on CodePen.

Saturday, February 20, 2021