- Notifications
You must be signed in to change notification settings - Fork2.4k
Clarify Space Complexity For DFS Traversal Of Binary Trees#3761
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Clarify Space Complexity For DFS Traversal Of Binary Trees#3761
Uh oh!
There was an error while loading.Please reload this page.
Conversation
Thanks for your research. The one thing that is challenging is to assign complexities that vary based on the intuition. For temporarily I have added the worst-case complexities and I'm also not 100% sure that all complexities are picture perfect (but doesn't lead to a wrong direction though). Once again, thank you for the work, there are slight modifications needed for complexities for Neetcode-150. I am adding articles for all the problems and will also improve them in iterative manner. |
That's very fair, thanks for taking a look@Srihari2222! Looking forward to any follow-up. |
@reywilliams Thanks, yeah this is a useful clarification I think. |
Uh oh!
There was an error while loading.Please reload this page.
articles/balanced-binary-tree.md
articles/binary-tree-diameter.md
articles/depth-of-binary-tree.md
articles/same-binary-tree.md
md
Note
All references to$\log$ here are$\log_2$ (as we usually assume with CS and its binary nature lol 😅 )
Sorry if this is a D1 yap sesh - I thought these would be helpful clarifications and learning and sharing them help me understand. I can add these to other DFS approaches as well, but I honestly didn't feel comfortable as I didn't use them or look over them. Should still be applicable as it is DFS though.
I wanted to clarify some space complexities for the DFS traversal of binary trees. This might help in evaluating what approach to use during an interview or the complexities of your chosen method.
Frommy understanding (please challenge this if need be), the DFS traversal of binary trees has space complexities as follows:
Best Case (Balanced Tree)
See this balanced binary tree here.
In this case, the height of the tree ($O(h)$ ) can be represented by$O(log(n))$ . This tree's height is$3$ and we know that$O(log_2(7))$ is around$3$ . We can make this "representation" as every node (except the 🍃 ) usually has two children.$h$ or$3$
With this height, the largest the call stack can go to is
Worst Case (Degenerate Tree / Linear Tree)
See this degenerate binary tree here (he's not a bad guy, just unbalanced 🥁 )
In this case, the height of the tree ($O(h)$ ) can be represented by$O(n)$ as every parent has one child. With this height, the largest the call stack can go to is$n$ or$5$ .