0

What will be the maximum length/space capacity of the queue when we run BFS on a tree? Is there a formula we can estimate it with?

I have tried using geometric series to estimate the rate of queue expansion, but I am not sure if it is the right approach.

  • Do we know the height of the tree? how many nodes ('children') each node can have? or there is no constraint on the number of children..? I assume `O(N)` (N is the total number of nodes), is not really a strict one, but it is certainty must be true... Do you need a stricter O\"theta" ? – CodeCop Feb 16 '21 at 13:42
  • "*I have tried using geometric series to estimate the rate of queue expansion, but I am not sure if it is the right approach.*" why wouldn't it be? Assuming a balanced tree, it should follow geometric progression. If it has at most `n` branches then at first level it has one node, the next one it's `n`, the next one it's `n*n`, the next one it's `n*n*n`, etc. That should be the upper limit, of course. If `n=5` but not all nodes have 5 children, then you'd have less. If the tree isn't balanced then that upper bound becomes too extreme, of course. – VLAZ Feb 16 '21 at 14:33

1 Answers1

0

If we assume a *Complete Binary Tree, then the maximum length of a queue during BFS would be the length of the last level in the tree (or the number of leaves). You can imagine that once you have dequeued all the elements in the second-last level of the tree, you will be left with a queue that has all the elements in the last level.

Since for a complete binary tree, the last level (the one with the leaves) will have the maximum number of nodes, that will correspond to the maximum length of the queue.

I think this idea could be extended to incomplete binary trees as well in the sense that the max length of the queue would be equal to the level in the tree that has the maximum number of nodes, but this will be an approximation, I think.

*(Complete Binary Tree: All leaves having the same depth and all internal nodes having two children)

  • This responses on this question provide good answers: https://stackoverflow.com/questions/17635950/space-complexity-of-level-order-traversal-traversal-using-a-queue – m-salman-05 Apr 14 '23 at 02:34