Can someone explain with an example how we can calculate the time and space complexity of both these traversal methods?
Also, how does recursive solution to depth first traversal affect the time and space complexity?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
BFS:
Time complexity is
O(|V|), where|V|is the number of nodes. You need to traverse all nodes.Space complexity is
O(|V|)as well – since at worst case you need to hold all vertices in the queue.DFS:
Time complexity is again
O(|V|), you need to traverse all nodes.Space complexity – depends on the implementation, a recursive implementation can have a
O(h)space complexity [worst case], wherehis the maximal depth of your tree.Using an iterative solution with a stack is actually the same as BFS, just using a stack instead of a queue – so you get both
O(|V|)time and space complexity.(*) Note that the space complexity and time complexity is a bit different for a tree than for a general graphs becase you do not need to maintain a
visitedset for a tree, and|E| = O(|V|), so the|E|factor is actually redundant.