Clarify Space Complexity For DFS Traversal Of Binary Trees #3761
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
From my 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$ .