Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is exactly mean log n height?

I came to know the height of Random-BST/Red-Black trees and some other trees are O(log n).

I wonder, how this can be. Lets say I have a tree like this

Binary tree

The height of the tree is essentially the depth of the tree, which is in this case will be 4 (leaving the parent depth). But how could people say that the height can be represented by O(log n) notion?

I'm very to algorithms, and this point is confusing me a lot. Where I'm missing the point?

like image 790
sriram Avatar asked Dec 12 '25 12:12

sriram


2 Answers

In algorithm complexity the variable n typically refers to the total number of items in a collection or involved in some calculation. In this case, n is the total number of nodes in the tree. So, in the picture you posted n=31. If the height of the tree is O(log n) that means that the height of the tree is proportional to the log of n. Since this is a binary tree, you'd use log base 2.

⌊log₂(31)⌋ = 4

Therefore, the height of the tree should be about 4—which is exactly the case in your example.

like image 81
DaoWen Avatar answered Dec 16 '25 00:12

DaoWen


As I explained in a comment, a binary tree can have multiple cases:

  • In the degenerate case, a binary tree is simply a chain, and its height is O(n).
  • In the best case (for most search algorithms), a complete binary tree has the property that for any node, the height of the subtrees are the same. In this case the length will be the floor of log(n) (base 2, or base k, for k branches). You can prove this by induction on the size of the tree (structural induction in the constructors)
  • In the general case you will have a mix of these, a tree constructed where any node has subtress with possibly different height.
like image 21
Kristopher Micinski Avatar answered Dec 16 '25 00:12

Kristopher Micinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!