So I know that the space complexity of a recursive in order traversal is O(h) and not O(n) as h = tree height and n = number of nodes in the tree.
Why is that? Lets say that this is the code for the traversal:
public void inorderPrint (TreeNode root) {
if (root == null) {
return;
}
inorderPrint(root.left);
System.out.println(root.data);
inorderPrint(root.right);
}
We are pushing n memory addresses to the call stack, therefore, the space complexity should be O(n).
What am I missing?
In recursive in-order traversal, we first process all nodes in the left subtree, then root node, and finally, we process all the nodes in the right subtree. Suppose we use a function inorder(root) with root as an input parameter.
The complexity of each of these Depth-first traversals is O(n+m).
The space complexity of a binary search tree is O ( n ) O(n) O(n) in both the average and the worst cases.
The recursion tree shows us that the results obtained from processing the two subtrees of the root N can be used to compute the result for the tree rooted at N. Similarly for other nodes. The leaves of this recursion tree would be fibonacci(1) or fibonacci(2) both of which represent the base cases for this recursion.
The addresses are removed from the stack when returning. This space is re-used when making a new call from a level closer to the root. So the maximum numbers of memory addresses on the stack at the same time is the tree height.
IMHO, you should treat the space complexity as O(n)
instead. While dealing with space and time complexities in Big O notation we always try to give the complexity value as a function of number of input elements which is n
in this case.
Also, if you consider the cases of right skewed binary tree or a left skewed binary then you would find this O(n)
space complexity as a fitting one. Have a look at below cases of right skewed binary tree:
1
/ \
2
/ \
3
Number of nodes, n = 3
Number of stack frames required in recursive traversal = 3
1
/ \
2
/ \
3
/ \
4
/ \
Number of nodes, n = 4
Number of stack frames required in recursive traversal = 4
So you can conclude that O(n)
is a fitting space complexity in such a worst case scenario (w.r.t. tree structure). In all other cases/types of trees number of stack frames required would always be less than n
. And that is how we express complexities. The actual space taken by all possible cases should always be less than or equal to the depicted function.
Also, in all cases always it will be O(h) <= O(n)
. So thinking the space complexity as O(n)
just gives us a uniform way of thinking in terms of input number of elements. Although, O(h)
space complexity is equally correct due to the reasons mentioned by @StefanHaustein in his answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With