简体   繁体   中英

Run time for inserting a binary search tree is n^2?

The book says the worst run time of inserting a binary search tree is n^2

I don't really get it.

I mean if you have 1, 2, 3, 4, 5, 6, 7, 8, 9

which is the worst case, isn't the worst case run time is O(n)?

(if value < node.data, go to left, if > node.data go right)

Can anyone explain? I would really appreciate that!


I think I got the answer now! because you need to go back to find if the new number is greater or smaller from the beginning.

But I have another question now, whats the worst case run time of building a AVL tree?

The book says build and sort a binary search tree is n(log n)

the worst depth of a AVL tree is log n

it never said what's the inserting time of a entire AVL tree.

anyone knows?

It is not O(n) because on each insertion you need to go through the whole tree to find a suitable location to place the new node.

For instance, at first you place a 1 at the head of the node. Then, to place the 2, you need to look at the 1 at the head and decide to add the 2 to the right of the head. Then, when adding the 3, you need to look at that 1 again, decide to go right, then look at the 2 and put the 3 on the right node of the 2.

So basically, each worst case insertion is O(k) (where k is the number elements already in the tree). To build the tree you need to do n insertions, so the whole operation takes 1+2+3+4+5+6...+n operations which is O(n^2/2) --> O(n^2) .

First of all, the depth of an AVL Tree:
Let N(h) denote the no. of nodes in an AVL Tree of height h.
N(h) >= 1+N(h-1) + N(h-2), this comes from the definition of the AVL Tree.
N(h) >= F(h)-1, where F(h) is the Fibonacci no.
N(h) >= {(1+sqrt(5)/2}^h,
therefore h <= log (with base=(1+sqrt(5))/2) n.
so h <= c logn. base=2;`
Now looking at the above input where we want to insert 1,2,3,...,n.
Now rotation will take place in constant time.
After every two element insertion, one rotation occurs. So no of rotations=n/2.
And every time we need to do logm comparisons where logm is the current height.
So total operations = c(log 1+ log 2+ log 3+ log 4+ .... +log n-1) + n/2
which is equal to c(log (n-1)!) + n/2
<= c(nlogn) + n/2 , which is nothing but O(nlogn).

PS:logn implies base of 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM