Here's the problem statement as stated on educative.io.
Given a binary tree and a number ‘S’, find all paths from root-to-leaf such that the sum of all the node values of each path equals ‘S’.
I understand the solution given to the problem and the time complexity portion. My confusion lies with the worst-case space complexity. The space complexity for the output array is calculated for a balanced binary tree and it's concluded that it's the same for an unbalanced binary tree without any explanation.
Here we have seven nodes (i.e., N = 7). Since, for binary trees, there exists only one path to reach any leaf node, we can easily say that total root-to-leaf paths in a binary tree can’t be more than the number of leaves. As we know that there can’t be more than (N+1)/2 leaves in a binary tree, therefore the maximum number of elements in allPaths will be O((N+1)/2) = O(N). Now, each of these paths can have many nodes in them. For a balanced binary tree (like above), each leaf node will be at maximum depth. As we know that the depth (or height) of a balanced binary tree is O(logN) we can say that, at the most, each path can have logN nodes in it. This means that the total size of the allPaths list will be O(N*logN). If the tree is not balanced, we will still have the same worst-case space complexity.
From the above discussion, we can conclude that our algorithm’s overall space complexity is O(N*logN).
Also, from the above discussion, since for each leaf node, in the worst case, we have to copy log(N) nodes to store its path; therefore, the time complexity of our algorithm will also be O(N*logN).
I drew out a couple of binary trees with 7, 8, 9, ... nodes and I'm able to create unbalanced trees that would require more space in the output array than it's balanced tree counterpart. Furthermore, the difference does not grow by a constant value.