Microsoft Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




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

This is just a simple question of converting a BST to a linked list (singly or doubly). You can find the answer to this by Googling online

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

While the actual code is non-intuitive, there is a very easy solution to this problem, if the parent pointer is available at each node:

1. Go to the left most node.
2. Repeatedly call Inorder Successor and before moving to that node, set it as the Right of the current node

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

In fact, below is the solution in C#, that solves this problem, even if the tree does not have a parent pointer for each node.

This code is going to create a doubly linked list (if the tree is a binary search tree, the resultant linked list will be sorted). It is super easy to modify it to create a singly linked list.

Code in C#:

public class BinarySearchTree
{

	public class Node
	{
		public int data;
		public Node left;	// In the doubly linked list, this will become previous pointer
		public Node right;	// And this will become next pointer
	}

	private Node root;		// Root of tree   

	private Node head;		// Head of doubly linked list
	private Node prev;		// Temporary pointer that stores the previous node, while linked list is being built

	public void ToDoublyLinkedList()
	{
		prev=null;
		ToDLL(root);

		// If you want to make the doubly linked list circular, uncomment the lines below:
		//head.left=prev;
		//prev.right=head;
	}

	private void ToDLL(Node node)
	{
		if(node==null) return;
		ToDLL(node.left);

		if(prev!=null)	// We are in the middle of inorder traversal.
		{
			prev.right=node;
			node.left=prev;		// Comment this line, if you want a singly linked list
		}
		else	// This is the first node in inorder traversal
		{
			head=node;
			head.left=null;		// Head should not point back to anything, since this is the first node
			node.left=null;		// This is already the case, but for the sake of code clarity, I am putting it here
		}

		// Set current node as prev (why?: imagine the recursive tree for this method. the next node is the inorder successor of this node)
		prev=node;
		
		ToDLL(node.right);
	}

}

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

Awesome solution. Nice work. Easily covers, singly, doubly and circular linked list (all cases)!

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

This post needs more votes, so it can bubble to the top. This is 100% working code

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

Thank you for this solution :)

- Dee January 15, 2012 | Flag
Comment hidden because of low score. Click to expand.
6
of 6 vote

Flatten( Tree root){
if(root == null)
return null;
else 
L = Flatten(root ->left);
R = Flatten(root-right);

root->right = R;
(last Node of L) -> Right = root;

return L;

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

return R should be there ?

- Anonymous August 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No It should be L.

- Manjesh April 09, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

void inorder(tree t)
{
if(t == NULL)
return;
inorder(t->left);
printf("%d ", t->val);
inorder(t->right);
}

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

Replace printf with linkedlist.add(t->val);
and write linkedlist.add function which adds the node at its tail.

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

flatten(node *ptr)
{
     if(ptr==null)return;

     node * alist=flatten(ptr->left);
     node *blist =flatten(ptr->right);
     node * tmp=alist;
     while(tmp->next!=null)tmp=tmp->next;
           tmp->next=ptr;
           tmp=ptr;
           tmp->next=blist;
           return alist;
           
}

this works correctly

- monika.agarwal712 January 24, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

is it a Doubly linked list ??
like left pointing to prev node and right pointing to next node ???

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

First Add all nodes in a queue in inorder.
Now go through the queue and assign right/left pointers on adjacent elements.
O(n) time

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

I am pretty sure they wanted it with O(1) space.

- sushant.singh1987 January 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

yes this is doubly link list.
I was asked to re arrange the existing tree.

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

Rearranging as in modifying the existing node in a link list format .. like
node1 -> right = node2
node2 -> right = node3 ?
You mean like this?

- Srikant Aggarwal January 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

hmm..
tis s my idea. (with one extra static variable pre) give ur suggestions..
do inorder traversal and store the first visiting node in variable pre.
now while visiting each node do the following
pre->right=current; // previous nodes next for first node (i.e pre=NULL) skip tis
current->left=pre; // current nodes previous
pre=current
will this work ???

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

I wanted to provide a solution that does not require any static variables outside of the recursion loop. That means you have to traverse the nodes to get to the last one before adding the next node, so it is definitely not more efficient than solutions using a static variable, but it is more self-contained.

public BinaryTreeNode FlattenInOrderTree(BinaryTreeNode currentNode)
        {
            BinaryTreeNode newNode = null;
            // Left
            if (currentNode.LeftChildNode != null) newNode = FlattenInOrderTree(currentNode.LeftChildNode);
            else return new BinaryTreeNode(currentNode.Value);
            // Middle
            BinaryTreeNode rightMostChildNode = newNode;
            while (rightMostChildNode.RightChildNode != null)
                rightMostChildNode = rightMostChildNode.RightChildNode;
            rightMostChildNode.RightChildNode = new BinaryTreeNode(currentNode.Value);
            rightMostChildNode.RightChildNode.ParentNode = rightMostChildNode;
            // Right
            if (currentNode.RightChildNode != null) rightMostChildNode.RightChildNode.RightChildNode = FlattenInOrderTree(currentNode.RightChildNode);
            rightMostChildNode.RightChildNode.RightChildNode.ParentNode = rightMostChildNode.RightChildNode;

            return newNode;
        }

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

Node* inorderList(Node* n)
{
    if(!n) return NULL;
    Node* l = inorderList(n->left);
    if(l) l->right = n;
    inorderList(n->right);
    return n;
}

- paks May 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If this is just a binary tree then we can add at the leaves. so, the complexity would be nothing but the addition of the second tree into the first tree.

If this is a bst, then we can add each of the nodes of the second bst into the first bst using the standard bst rules.

- Pavan Dittakavi August 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Node *flatten(Node *root)
{
if (root)
{
root = flatten(root->left);
if (root)
{
add_list(root);
root = flatten(root->right);
}
return NULL;
}

- BB August 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry for the above program as I omitted closing brace properly.
Here is the correct version of it:
Node *flatten(Node *root)
{
if (root)
{
root = flatten(root->left);
if (root)
{
add_list(root);
root = flatten(root->right);
}
}
return NULL;
}

- BB August 19, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def flatten_util(self,root):
        if root:
            # if root.left == None and root.right == None:
            #     return root, root
    
            append = root
            x=root.right
            if root.left:
                left_ll, left_last = self.flatten_util(root.left)
                root.right = left_ll
                root.left = None
                append = left_last
            if x:
                right_ll, right_last = self.flatten_util(x)
                append.right = right_ll
                append.left = None
                append = right_last
            #print_ll(root)
            #print
            return root, append

- sumitgaur.iiita December 19, 2016 | 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