What is the time complexity of the best case to insert a new node into a minimum-level BST with n nodes?

StackOverflow https://stackoverflow.com//questions/22078331

  •  24-12-2019
  •  | 
  •  

Question

I am learning about algo complexity and calculating time complexity. the question is

What is the time complexity of the best case to insert a new node into a minimum-level BST with n nodes? Explain. (Hint: You may draw a diagram as part of your solution.)

Can you please explain in details how you would solve this question and similar questions?

my attempt:

for time complexity we have 2 questions, how many times and what does it cost.

How many times: there will be one element to check so => O(1) how much does it cost? how many times?

now I am stuck here (pretty early), I am assuming that since its a tree, there will be n/2 elements after the first comparison and it keeps splitting into half.

Was it helpful?

Solution

Consider the following minimum-height BST (any binary tree with 8 nodes has at least 4 levels, thus it has the minimum height).

         8
        / 
       4
     /   \
    2     6
   / \   / \
  1   3 5   7

Now let's say you insert the value 9, it will go straight to the right side of the root.

To generalize this example: a BST which has a right child or left child which are complete trees- is a minimum height BST. If the other side is empty, any value that you'll insert which will be greater\lesser to the node will be added directly to the root's right\left child. in this case the insert will take O(1) time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top