Amazon Interview Question for Software Engineer / Developers


Country: India
Interview Type: Phone Interview




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

USING 2 STACK SOLUTION :::::

public void printZigZag(Node root) {
    Stack<Node> s1 = new Stack<Node>();
    Stack<Node> s2 = new Stack<Node>();
    Node current = null;
    s1.push(root);
    int i = 0;
    while (!s1.empty() || !s2.empty()) {
     // while s1 is not empty...keep pushing to s2 and every alternate time, print the push
      while (!s1.empty()) {
        if (i % 2 == 0) {
          System.out.println(s1.peek().iData);
        }
        s2.push(s1.pop());
      }
      while (!s2.isEmpty()) {
        // while s2 is not empty, keep pushing s2 elements children to s1 and also print alternatively
        current = s2.pop();
        if (i % 2 != 0) {
          System.out.println(current.iData);
        }
        if(current.rightChild!=null)s1.push(current.rightChild);
        if(current.leftChild!=null)s1.push(current.leftChild);
      }
      ++i;
    }
  }

- Priyank Mundra January 14, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I got this earlier, but was implementing with list.Two stacks have better complexity O(n)

- gupta January 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Use one stack only , just keep track of level.Say when level%2==0 push left first then right, in else case do opposite , also make sure that u r printing out while adding to the stack.

- aaman.singh85 April 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 3 vote

You just need to do BFS... maintain a queue and print all childs.
In case of mirror image you need to make sure you put the right child in the queue first.
Code is below...

static void printTreebylevel(TreeNode root,boolean mirror){
		if(root == null)
			return;
		
		LinkedList<TreeNode> list = new LinkedList<TreeNode>();
		list.add(root);
		
		while(list.isEmpty() == false){
			int n = list.size();
			String s = "";
			boolean alternate  = true;
			while(n!=0){
				TreeNode p = (TreeNode) list.remove();
				n--;
				s = s + p.data + " ";
				if(mirror == false){
					if(p.left!=null)
						list.add(p.left);
					if(p.right!=null)
						list.add(p.right);
				}else{
					if(alternate==false){
						if(p.right!=null)
							list.add(p.right);
						if(p.left!=null)
							list.add(p.left);
					}else{
						if(p.right!=null)
							list.add(p.right);
						if(p.left!=null)
							list.add(p.left);
					}
					alternate = !alternate;
				}
					
			}
			System.out.println(s);
		}
		
	}

- loveCoding January 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The question doesn't ask for mirroring every level. It asks for mirroring every other level. You can see this in the given example.

This means, it's not just about processing the right child first.

- crdmp January 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Updated the code above please have a look, we can have one flag alrernate to manage that

- loveCoding January 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think alternate = !alternate should be outside the inner while loop because alternate should only change once you start a new level, not after each processed node.

Also, reversing the children of a node isn't enough. You have to reverse the whole level. Because of this, I think it's necessary to use a stack inside the inner while loop.

Of course, I might be wrong but the way I read this problem, and as far as I understand your code, that's my comment.

- crdmp January 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think a stack is need.

print(node* root,bool mirrored){
  queue<node*> bfs;
  bfs.push(root);
  bool alternate=false;
  while(!bfs.empty()){
      stack<int> st;
      int sz = bfs.size();
      while(sz--){
        node* cur = bfs.front();
        bfs.pop();
        if(mirrored&&alternate)
          st.push(cur->value);
        else
          printf("%d ",cur->value);
        if(cur->left!=NULL)
          bfs.push(cur->left);
        if(cur->right!=NULL)
          bfs.push(cur->right);
      }
      while(!st.empty()){
        printf("%d ",st.top());
        st.pop();
      }
      alternate=!alternate;
      printf("\n");
  }
  return;
}

- Karthik January 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Here is a good algo for the first part,

puddleofriddles.blogspot.com/2012/01/print-binary-tree-level-by-level-with.html

- Anonymous January 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Second part is a example of zigzag traversal , that can be achieved with the help of 2 stacks !

- Nitin January 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

use a queue and inqueue the node with level information... transverse the tree using the node which we dqueue from tree...
steps 1 : inqueue the root node with level 0... then loop until the queue is empty..
step2 : Dqueue the tail node from queue and inqueue the child of its in the order left then right along with the level as Dqueue_node->level +1.
step 3 : if the level is same as the previously dqueued node then print it and go to nest node in queue else change the line and print it, also increase the previously printed node by 1 ans go to next node in queue.

in other part of question you can use a additional stack to get the mirror image depending on the level as odd and even. I mean to say for odd level if we want to get a image then dqueue the node untill we get the level 1, inqueue the child as left and right then push the value of node in stack. ones the level is complete pop the elements from stake and print it.
In case of even level don't push the node in stake and just print it after inqueing the child's.

- Anonymous January 14, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

edition in first line
"use a queue and inqueue the node with level information... transverse the tree using the node which we dqueue from queue(not tree)...

- Sanjay Kumar January 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

@Manan, I doubt that the above solution works.
Because " TreeNode p = (TreeNode) list.remove(); " statement wouldn't ensure that you always referring to internal nodes.
Also this isn't a linear list. It is a tree.

So , if you can elaborate on this solution , it will be good.

- Vijay Rajanna January 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think we just traverse the three and keep track of the level where we are. If the current level is the necessary level => print the content.

- sergey.a.kabanov January 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

What about this? I just use a list of nodes and an alternate variable.

public static void PrintLevelsAlternateMirror(KNode root)
{
	if(root == null)
		return;

	List<KNode> current = new List<KNode>();
	current.Add(root);
	bool alternate = false;

	while(current.Count > 0)
	{
		if(alternate)
		{
			for(int i  = current.Count-1; i >= 0; i--)
{
	Console.Write(current[i].value + “ “);
}
		}
		else
		{
			for(int i  = 0; i < current.Count - 1; i++)
{
	Console.Write(current[i].value + “ “);
}		
}
Console.WriteLine();
		List<KNode> newList = new List<KNode>();
		for(int i = 0; i < current.Count-1; i++)
		{
			if(current[i].left != null)
				newList.Add(current[i].left);
			if(current[i].right != null)
				newList.Add(current[i].right);
		}

		current = newList;
		// swap
		alternate = (alternate) ? false : true;
		
	}
}

- Anonymous January 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <deque>
#include <iostream>
using namespace std;

void PrintLevel(TreeNode* root)
{
    if (root == NULL)
         return;
    deque<TreeNode*> q;
    q.push_back(root);
    while (!q.empty()) {
        int n = q.size();
        while (n != 0) {
             TreeNode* p = q.front();
             q.pop_front();
             cout << p->data << " ";
             if (p->left)
                  q.push_back(p->left);
             if (p->right)
                  q.push_back(p->right);
             --n;
         }
         cout << endl;
    }
}

- seek January 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void level_by_traversal_fromtop(struct node* ele)
{
if(ele == NULL)
return ;
if(ele->lptr!=NULL)
{
stack_node *nw = new stack_node();
nw->ptr = ele->lptr;
nw->next = NULL;
if(first == NULL)
first =tail=nw;
else
{
tail->next = nw;
tail =nw;
}
}
if(ele->rptr !=NULL)
{
stack_node *nw = new stack_node();
nw->ptr = ele->rptr;
nw->next = NULL;
if(first == NULL)
first =tail=nw;
else
{
tail->next = nw;
tail =nw;
}
}
cout<<ele->data<<" ";
if(first !=NULL)
{
stack_node *temp =first;
node *nd = first->ptr;
first = first->next;
delete temp;
level_by_traversal_fromtop(nd);
}

}

- Anonymous April 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

struct node* mirror(struct node* root)
{
	if(root==NULL)
	{
		return NULL;
	}
	struct node *l,*r;
	l= mirror(root->lptr);
	r= mirror(root->rptr);
	root->lptr = r;
	root->rptr=l;
	return root;
}

- Anonymous April 08, 2012 | Flag Reply


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