Interview questions DS

1. Write a program to add sum of all left most leaf node in a tree.

In this example you have to add the nodes 2,5 & 4

Answer:

enum direction{
    left=1,
    right
};


int calculateleftmost(struct tree* root, direction d)
{
    int  ls=0, rs =0;
    if(root->left == NULL && root->right == NULL)
    {
        if(d == left)
        {
            return root->data;
        }
    }
    if(root == NULL)
        return 0;
    ls = calculateleftmost(tree->left, left);
    lr = calculateleftmost(tree->right, right)
    return ls+rs;
}


2.  How to get the Kth largest number in an unsorted array

Answer:

soluton 1: 2 nested loop
     outer loop is from 0-K & innerloop is from 0-n & use bubble sort the    array[n-k] is the answer.

order is k*n
solution 2:  use K loops one after another then get number arr[n-3].
solution 3: traverse the array & create a BST. in that tree perform the tree traverse operation in (right, root left ) order then find the 3rd most element
solution 4: create a temporary flag array having maximum limit of the current array. traverse the current array and get the value & mark the flag array on the corresponding index. Then traverse the flag array from maximum range to down when the flag is 'true' then increase the counter. When counter is 3 that value is 3rd largest number of the array
This approach is better is we compare the performance as it take o(n) but this solution contain extra space.


3. count number of 1 bits in a number
Answer: using right shift operation and '&' operation with 1. :)



 

Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Interview questions