Good for you, actually double-checking the reasoning instead of taking it on faith that it is correct!
The method of analysis for a balanced binary tree is correct for an unbalanced one as well. But the unbalanced one can have depth O(N)
. And therefore the maximum space is the number of paths times the depth, which is O(N) * O(N) = O(N^2)
.
For an unbalanced binary tree that reaches the worst case, we will create a tree all of those nodes have value 1 of size a power of 2. The first half the nodes are a straight line leading to the right. The other half are a perfectly balanced binary tree from the end of the first half. This tree will have O(N/4)
paths of weight N/2 + log_2(N/2)
and will indeed require O(N^2)
space.
I would strongly suggest pointing out the mistake to them so that they can correct it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…