edited by
8,818 views
49 votes
49 votes

Suppose there is a balanced binary search tree with $n$ nodes, where at each node, in addition to the key, we store the number of elements in the sub tree rooted at that node.

Now, given two elements $a$ and $b$, such that $a < b$, we want to find the number of elements $x$ in the tree that lie between $a$ and $b$, that is, $a \leq x \leq b$. This can be done with (choose the best solution).

  1. $O(\log n)$  comparisons and $O(\log n)$ additions.
  2. $O(\log n)$ comparisons but no further additions.
  3. $O \left (\sqrt{n} \right )$ comparisons but $O(\log  n)$ additions.
  4. $O(\log  n)$ comparisons but a constant number of additions.
  5. $O(n)$ comparisons and $O(n)$ additions, using depth-first- search.
edited by

5 Answers

0 votes
0 votes

Number of comparisons will be O(logn) and additions will be constant.

Algorithm:

Step 1: First find out the lowest common ancestor of a and b.

            https://afteracademy.com/blog/lowest-common-ancestor-of-a-binary-tree

            O(logn)

Step 2: then find out the parent of both a and b using given algorithm

             https://www.geeksforgeeks.org/find-the-parent-of-a-node-in-the-given-binary-tree/

            O(logn)

Step 3: then use the given logic for finding out the number of additions required.

             N(p) : denotes no of children in its subtree ( it is stored in each node)

             P(p) : denotes parent of node p

             Z = no of nodes between [a,b]

             root is the lowest common ancestor of a and b.

             case 1 : if a is left child of its parent and b is right child of its parent

             Z= N(root) - ( N(a->left) + 1) - ( N(b->right) +1 ) +1

             case 2: a is right and b is right child of their parent

             Z = N(root) - ( N(a->left) + 1) - ( N( P(a) -> left ) +1 ) - ( N(b->right) +1 ) +1

             case 3 : if a is left child of its parent and b is left child of its parent

             Z= N(root) - ( N(a->left) + 1) - ( N(b->right) +1 ) - ( N ( P(b)->right ) +1)  +1

             case 4: a is right and b is left child of their parent

             Z = N(root) - ( N(a->left) + 1) - ( N( P(a) -> left ) +1 ) - ( N(b->right) +1 ) -

                   ( N ( P(b)->right ) +1)+1

            So only a constant no of additions required.

 

              

Answer:

Related questions