Amazon Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
0
of 0 vote

Create a nXn matrix where n is the size of the Binary tree.
Do a BFS, whenever you are adding nodes to the queue, set the indexes where represent the current node and its parents. Note that the parents are already set for the current node.

- Ravi May 26, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Or a DFS with a stack would also work.

- memo May 27, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

why do you need BFS?
this can be done using a inorder traversal
first declare a n*n matrix..
then define a function as follows.
void convert2matrix(node *root, node *parent){
if(root != NULL){
if(par != NULL)
matrix[par->data][root->data] = 1;
convert2matrix(root->left, root);
convert2matrix(root->right, root);
}
}

invoke this function using : convert2matrix(root, NULL);
i think this will work fine..

- Anonymous May 26, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

just a bit of correction above..
replace par with parent
and
replace statement matrix[par->data][root->data] = 1 with matrix[root->data][parent->data] = 1

- Anonymous May 26, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This method seems to be wrong as it will just put 1 on the immediate parent and not on the super parent. For example for the node D it will say its parent is only B and put 1 only in that slot in the matrix(DB) and not put it in (DA)

Correct me if I am wrong??

- Anonymous May 30, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think you are right.
After the tree traversal finishes, the matrix can be easily processed to set 1 for all the non-immediate parents.

- jiangok2006 October 07, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

My solution was... do any traversal and save all node in a hash table such that <k,v> = <node, its parent>

Then populate the matrix using the table.
Space complexity = O(n)
Running time complexity = O(nlogn)

- Arang May 26, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

We can implement it by using the array representation of binary tree.In array representation the 0th element is the root, the index at 1 is left child of the root and at index 2 is right child of the root... and so on.
So if a node's index no is index then its left child will be 2*index + 1 , right child will be 2*index + 2, node's parent will be (index - 1)/2 --> integer division with no remainder. Hence the code goes like following
initialize the array as arr[numOfNodes][numOfNodes]

Int parent Index = 0;
For(int i= numOfNodes - 1 ; i >= 0; i--){

	Do{
		Parent Index = (I - 1)/2;
		Arr[i][parentIndex] = 1;

	}while( parentIndex > 0)
}

correct me if I am wrong.

- Priyanka May 27, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

seems like brilliant soln to me

- PM June 06, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is a great idea, however, it will only work for proper binary trees. If a non-leaf node has only 1 descendant, the array will need to contain a null value for that node.

Once the full matrix is constructed, then all null columns/rows can be removed.

- Anurag June 07, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

correct solution can be this:
void convert2matrix(node *root, node *parent){
if(root != NULL)
{
if(parent != NULL)
{
memcpy(matrix[root->data], matrix[parent->data], n*sizeof(int));
matrix[root->data][parent->data] = 1;
}

convert2matrix(root->left, root);
convert2matrix(root->right, root);
}
}

basically, copy the parent data . and just set matrix[root][parent] = 1;

- bansal.cool May 27, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Like this solution

- jiangok2006 October 07, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

STACK* stack2 = createStack();
Int createMatrix(STACK* stack, NODE* node)
{
NODE* tmp;
If(node->left != NULL || node->right != NULL)
{
Stack->push(node);
If(node->left != NULL) createMatrix(stack, node->left);
If(node->right != NULL) createMatrix(stack, node->right);
}
While(!stack->empty())
{
Tmp = stack->pop();
SetMatrix(tmp->data, node->data);
Stack2->push(tmp);
}
While(!(stack2->empty())
{
Tmp = stack->pop();
Stack2->push(tmp);
}
Stack->pop();
Return;
}

- chenming831@gmail.com May 29, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void createMatrix(treenode *root, int matrix[][], int n) //n is size of tree
{  
   int i;
   if (!root) return;
   if (root->left) {
	matrix[root->left][root->data] = 1;
            for (i=0; i<n; i++) {
                if (matrix[root->data][i])
                     matrix[root->left][i] = 1;
            }
            createMatrix(root->left, matrix, n);
    }
   if (root->right) {
	matrix[root->right][root->data] = 1;
            for (i=0; i<n; i++) {
                if (matrix[root->data][i])
                     matrix[root->right][i] = 1;
            }
            createMatrix(root->right, matrix, n);
    }
}

- cubic June 04, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

fill_matrix(int i,Node *root){
if(root){
Parent = [i/2];
if(Parent>0){
while(Parent > 0){
A[i][Parent]=1;
Parent=[Parent/2];
}
}
fill_matrix(2*i,root->left);
fill_matrix(2*i+1,root->right);
}
}



}



}



}

- Anonymous June 05, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

fill_matrix(int i,Node *root){
if(root){
Parent = [i/2];
if(Parent>0){
while(Parent > 0){
A[i][Parent]=1;
Parent=[Parent/2];
}
}
fill_matrix(2*i,root->left);
fill_matrix(2*i+1,root->right);
}
}



}



}



}

- Prashant Golash June 05, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Very impressive... Good job..

- Muntasir July 20, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Prashant's answer is best here I guess. But, let me give my two cents.

Call matrix by matrix(root, new ArrayList<BinaryTree());

I am just print the nodes, you can use a matrix in case you life.

private static void matrix(BinaryTree root, ArrayList<BinaryTree> list){
		
		if(root == null){
			return;
		}
		
		list.add(root);
		matrix(root.left, list);
		matrix(root.right, list);
		list.remove(list.size()-1);
		System.out.println();
		for(int i = 0 ; i < list.size();i++){
			BinaryTree parent = list.get(i);
			System.out.print("[" + parent.data + "->" + root.data + "]");
		}
		

	}

- ekapil2 November 16, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The idea is to pass the parent to both left and right child and when you backtrack from the child just print all its parents.

- ekapil2 November 16, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think Ravi's answer seems good. While doing a BFS, the nodes that are enqueued can be set in the matrix.

- Anonymous June 14, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void VerticalSum(TreeNode* node,int column, int *sum)
{
	if(node == null)
	{
		return ;
	}
	
	sum[column]+= node->Data;

	VerticalSum(node->Left,column-1,sum);
	VerticalSum(node->Right,column+1,sum);

	return ;

}
void VerticalSum()
{
	int sum[1000]={0};

	VerticalSum(_root,499,sum);
	int i = 499;
	while(sum[i] != 0) i--;
	i++;

	for(int j=1;sum[i]!=0;i++,j++)
	{
		printf("Vertical-%d = %d\n",j,sum[i]);
	}

}

- xyz August 04, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

please ignore this

- xyz August 04, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

list={} //infact a vector
fun(root)
{
if(!root) return;
else{
for all elements X in list
mat[root->data][X->data]=1;
list.push(root);
fun(root->left);
fun(root->right);
list.remove(root);
}

}

- Anonymous September 26, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//assume matrix is big enough matrix initialized with 0.
void f(NODE* root, int** matrix)
{
  Stack stack;
  int[] ChildCounts[];
  (NODE*)[] Nodes;
 
  int p1=0, p2=0;  
  
  stack.push(root);
  while(!stack.empty())
  {
    NODE *node = stack.pop();
    ChildCounts[p2]=count(node's children);
    Nodes[p2++]=node;
    stack.push(node->Children); //handle left and right respectively

    if node != root
       NODE* parent = Nodes[p1];
       if(--ChildCounts[p1] == 0)
           p1++;
       //function GetIndex gets index of this node from Nodes array.
       matrix[GetIndex(node)][GetIndex(parent)]=1;       

       for(n = GetIndex(parent)-1 to 0)
         if matrix[parent][n]==1
             matrix[node][n]=1  
  } 
}

- jiangok2006 October 06, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

typo: the stack should be queue. I am using BFS.

- jiangok2006 October 06, 2010 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More