Showing posts with label Salesforce. Show all posts
Showing posts with label Salesforce. Show all posts

Saturday, September 3, 2011

Salesforce Question: Spiral Order Traversal of Binary Tree


void BinaryTree::SpiralTraversal(Node* root)
{
    stack<Node*> stack1, stack2;
    stack1.push(root);
    while(!stack1.empty() || !stack2.empty())
    {
        while(!stack1.empty())
        {
            Node* node1 = stack1.top();
            stack1.pop();
            cout<<node1->data<<'\n';
            if(node1->right)
                stack2.push(node1->right);
            if(node1->left)
                stack2.push(node1->left);
        }
        while(!stack2.empty())
        {
            Node* node2 = stack2.top();
            stack2.pop();
            cout<<node2->data<<'\n';
            if(node2->left)
                stack1.push(node2->left);
            if(node2->right)
                stack1.push(node2->right);
        }
    }
}

Thursday, August 4, 2011

Salesforce Question: Given two arrays A and B, find out elments of B which are not in A

Hash all the elements of A.
if B[i] is not in hash add into the result. 0<=i<sizeof(B)


Salesforce Question: In an unsorted array, find a pair (a, b) such that a+b = k

It was given that pair will be unique.
void FindPair(int* arr, int size, int sum)
{
    for(int i=0; i<size; ++i)
          hash[arr[i]] = 1;
    for(int i=0; i<size; ++i)
    {
           if(hash[sum-arr[i]])
                cout<<"Pair found ( " <<arr[i]<<", "<<sum-arr[i]<<" )";
      }
}