If i construct a binary search tree adding the following values in order:
10, 7, 16, 12, 5, 11, 2, 20, 1, 14
I get a tree of height 5. Is there a method (other than trial and error) that I can use to determine an ordering of the integers that would create a tree of height 4?
I haven’t thought this through completely, but one way of getting a tree of specific depth is to sort your elements before inserting them: i.e. sorting then inserting
Nelements into a binary search tree will produce a tree of depthN.You might be able to:
K=4of them to produce a tree of depthK(Of course, choosing which
Kelements to start with and a strategy for inserting the remaining elements is the tricky part — but maybe this would be a start?)Edit: I think a general solution is possible, assuming
Kis big enough. How about this:10, 7, 16, 12, 5, 11, 2, 20, 1, 141, 2, 5, 7, 10, 11, 12, 14, 16, 20For example, after sorting and inserting the last 4:
…then after inserting the last 3:
…then after the last 2:
…and finally, after inserting the last element:
…you’re left with a BST of height K=4.
Note that this approach will only work when
Kis big enough — specifically, whenK(K+1)/2 >= N.