Microsoft Interview Question for Software Engineer / Developers






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

reverse(node* ptr)
{
   if(ptr==null)
        return;
  else{

  reverse(ptr->left);
  reverse(ptr->right);
  node* t= ptr->left;
  ptr->left=ptr->right;
  ptr->right=t;
  return;
  }
}

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

Finally a brute force method BigO is (3N) 2N for Traversal and N for pointer adjustment.
I accept it takes more memory, so champs please come up with something more optimize and elegant.

/// <summary>
/// Reverses a Balanced Bindary Tree
/// </summary>
/// <param name="rroot"></param>
/// <returns></returns>
private ArrayList ReverseTree(TNode root)
{
ArrayList nodes = new ArrayList();
ArrayList heads = new ArrayList();
TNode curr, left, right;

PostOrder_Reverse(root, nodes);

for (int i = 0; i < nodes.Count; i++)
{
curr = nodes[i] as TNode;

if (curr.right == null)
{
heads.Add(curr);
continue;
}
else
{
left = curr.left;
left.left = curr;
left.right = null;
curr.left = null;

right = curr.right;
right.left = curr;
right.right = null;
curr.right = null;
}
}

return heads;
}


/// <summary>
/// Populate input ArrayList while traversing in postorder (L R N)
/// </summary>
/// <param name="ptr"></param>
/// <param name="nodes"> </param>
private void PostOrder_Reverse(TNode ptr, ArrayList nodes)
{
if (ptr != null)
{
PostOrder_Reverse(ptr.left, nodes);
PostOrder_Reverse(ptr.right, nodes);
nodes.Add(ptr);
}
}

- pk September 13, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

I think we should do sth like post-order traversal...
reverse(treeptr *ptr, treeptr parent)//Call as reverse(&root,NULL);
{
if(*ptr)
{
if((*ptr)->left || (*ptr)->right)
{
parent = *ptr;
}
reverse((*ptr)->left);
reverse((*ptr)->right);
(*ptr)->left = parent;
(*ptr)->right = NULL;
}
}

- Shwetank Gupta October 09, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Can you specify more clearly what's a "revert Binary tree"?

- Fred September 13, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Node[] Reverse(Node root)

so for the tree below, out put shd be Array with 4 roots L1,L2,L3,L4

Input Tree:

R
C1 C2
L1 L2 L3 L4

Output tree: (Its No more binary tree, looks like a 4 linked list where L1,L2 share common Node C1 and R, and L3 L4 has common node C2 and R)

L1 L2 L3 L4
C1 C2
R

- pk September 13, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Usually 'reversing of a binary tree' means mirroring of the tree. So reversing of the tree:

a
 / \
b  c
     \
     d

is the tree

a
   / \
  c  b
 /
d

- Aleksey.M November 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

use bfs level order traversing .
save all the same level nodes into a array(level wise).
now you can print the array in reverse order.

- xmagics September 13, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

its not printing, its about changing the pointers.

- pk September 13, 2008 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

code is in C# and "///" denote commented line

- pk September 13, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Please comment

void ReveseTree(Tree** root)
{
reverseT(root,NULL);
}

void ReverseT(Tree** root, Tree* parent)
{
if(!root) return NULL;
Tree* node=*root;
if(!node) printTree(parent);

Tree* left=NULL;
Tree* right=NULL;

if(node)
{
*root=node;
left=node->left;
right=node->right;
node->left=parent;
parent=node;
reverseT(left,parent);
reverseT(right,parent);
}
}

void printTree(Tree* root)
{
//any order traverse here
}

- Jackie September 15, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a correction
void ReveseTree(Tree** root)
{
reverseT(root,NULL);
}

void ReverseT(Tree** root, Tree* parent)
{
if(!root) return NULL;
Tree* node=*root;
if(!node)
{printTree(parent);
return;
}


Tree* left=NULL;
Tree* right=NULL;

if(node)
{
*root=node;
left=node->left;
right=node->right;
node->left=parent;
parent=node;
reverseT(left,parent);
reverseT(right,parent);
}
}

void printTree(Tree* root)
{
//any order traverse here
}

- Jackie September 15, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sorry more correction.
print and return when it is a leaf node;otherwise, continue recursion
void ReveseTree(Tree** root)
{
reverseT(root,NULL);
}

void ReverseT(Tree** root, Tree* parent)
{
if(!root) return NULL;
Tree* node=*root;

Tree* left=NULL;
Tree* right=NULL;

if(node)
{
*root=node;
left=node->left;
right=node->right;
node->left=parent;
if(!right&&!left)
{
printTree(node);
return;
}
parent=node;
reverseT(left,parent);
reverseT(right,parent);
}
}

void printTree(Tree* root)
{
//any order traverse here
}

- Jackie September 15, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

One problem i see is you will lose the tree.
As after reversal it will multiple roots, so you Reverse() shd return a Array of root nodes. so for example above Reverse() return array
heads[0]=L1
heads[1]=L2
heads[2]=L3
heads[3]=L4

- pk September 15, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Did it by any chance mean doing a mirror image of the tree OR in other words rotating it around the root, so if the storing order is left child < parent < right child (increasing order left to right), then reversal will result in left child > parent > right child (increasing order right to left) ?

- hipy September 17, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

hipy... see the example in 3rd post. its not the way u said.

In ur words :)
Flip the tree vertically ... and change the --> to <---

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

storing of the reversed tree is trivial, just replace the print statement with some code to store them

- @pk by Jackie September 17, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

i think we shld go for breadth first search on the given complete binary tree.. and storing each node in an array . (R C1 C2 L1 L2 L3 L4)

now we can generate the tree as .. at any level i the node will have two parents at i+1 th level ie left parent and right parent . and so on ..
for eg . R will have L1 as left parent and L2 as Right parent .
L1 will have C1 as left parent and C2 as right parent .

if array Nodes [] stores the node then ..
for i th node in the array .
the Left parent wud be i*2
the right parent wud be i*2+1

this way we can make the given tree.

Comments are invited

- mine solution September 20, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think this is not that complicated. Do things like the following,
Just use the left link as the next pointer.
Node[] reverseTree(node *r){
//first get the number of leaves, create an array nodes[];
reverse(r, nodes);
return nodes;
}

Node *reverse(Node *r, nodes){
static int cnt = 0;
if(!r) return;
Node *left = reverse(r->left, nodes);
Node *right = reverse(r->right, nodes);
if(!left && !right){ nodes[cnt++] = r; return r;}
if(left) left->left = r;
if(right) right->left = r;
return r;
}

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

/*
root -> binary tree handle
i -> no. of root handles in the array (when the function returns), passed in as a reference
array -> container for the root's to be returned.
*/


node *array[100];
int i(0);
reverse_binarytree(array, root, i);
// loop through array for i iteration's and print out each as a regular linked list.



int reverse_binarytree(node** array, node* root, int & i){
if(!root)
return 0;
if((!root->lptr) && (!root->rptr)){
array[i++] = root;
return 0;
}
if(root->lptr) reverse_binarytree(array, root->lptr,i);
if(root->rptr) reverse_binarytree(array, root->rptr,i);
if(root->lptr) root->lptr->lptr = root;
if(root->rptr)root->rptr->lptr = root;
root->lptr=root->rptr=0;
return 0;
}

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

will this approach work:

reverse( root )
{
//Check of the left child is a leaf
if ( root->left != NULL and
root->left->left == NULL and
root->left->right == NULL )
root->left->right = root ;
root->left = NULL ;
if( root->right != NULL and
root->right->left == NULL and
root->right->right === NULL )
root->right->left = root ;
root->right = NULL
return ;
}

reverse ( root->left ) ;
root->left->right = root ;
reverse ( root->right ) ;
root->right->left = root ;
}

- Anonymous November 10, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Please comment:

reverse(node *node){
node *tmp;

if(node==NULL)
return NULL;
if(node->left) {
tmp=node->left;
tmp->right=node;
node->left=NULL;
reverse(tmp);
}
if(node->right) {
tmp=node->right;
tmp->left=node;
node->right=NULL;
reverse(tmp);
}
}

- tuesday420 November 10, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

guys avoid posting crappy bunch of codes without any explanation

- Anonymous September 29, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How about you try and solve it yourself without any help? If you do get the job then your incompetence and reliance on other people will be found out quite quickly.

- Anonymous February 09, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

/// <summary>
        /// Reverse a Binary Tree (not BST)
        /// Interviewer started with giving me a sample of 
        /// balance binary tree with Depth 3 i.e. total 7 nodes.
        /// </summary>
        /// <returns></returns>
        public List<node> Reverse()
        {
            list = new List<node>();
            ReverseTree(root, null);
            return list; 
        }

        private void ReverseTree(node rootptr,node rootroot)
        {
            node temp;
            if (rootptr.left != null)
            {
                ReverseTree(rootptr.left,rootptr);
            }

            if (rootptr.right != null)
            {
                ReverseTree(rootptr.right,rootptr);
            }

            if ((rootptr.left == null) && (rootptr.right == null))
            {
                list.Add(rootptr);
            }

            if (rootroot != null)
                rootptr.left = rootroot;
         }

- pk October 25, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Reverse binary tree is nothing but mirror image of binary tree.
look at the link "en.literateprograms.org/Binary_tree_(Scheme)"

- Naga Samrat Chowdary, Narla January 01, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverse (Node *node)
{
    if (node == NULL)
        return;
    if (node->left != NULL && node->left->left == NULL && node->left->right == NULL)
    {
        node->left->right = node;
        node->left = 0;
    }
    if (node->right != NULL && node->right->left == NULL && node->right->right == NULL)
    {
        node->right->left = node;
        node->right = 0;
        if (node->left == NULL)
            return;
    }
    if (node->left == NULL && node->right == NULL)
        return;
    if (node->left)
    {
        reverse (node->left);
        node->left->right = node;
        node->left = NULL;
    }
    if (node->right)
    {
        reverse (node->right);
        node->right->left = node;
        node->right = 0;
    }
}

- Siraj January 06, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private Node<T> reverse(Node<T> root) {
if (root == null) {
return null;
} else {
Node<T> left = root.getRight();
root.setRight(reverse(root.getLeft()));
root.setLeft(reverse(left));
}

return root;
}

- ?? September 09, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverse(Node *n) {
if (n == null) return;
if ( (n->left != null) && (n->right !=null)) {
Node *t = node->left;
node->left = node->right;
node->right = t;
}

if (node->left !=null) {
reverse(node->left);
}

if (node->right != null) {
reverse(node->right);
}
}

- Anonymous March 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My solution is a recursive traversal with recording the parent node of the current node and whether the current node is the left child of its parent node. A test case and class TreeNode are attached also.

public class TreeNode
{
	public TreeNode left=null;
	public TreeNode right=null;
	int val;
	public TreeNode(int v)
	{
		val=v;
	}
	public String toString()
	{
		return String.format("[TreeNode: val=%d]", val);
	}
	public String toStringAll()
	{
		return String.format("[TreeNode: val=%d, left=%s, right=%s]", val, 
				(left!=null) ? left.toStringAll() : null, 
				(right!=null) ? right.toStringAll() : null);
	}
}
public class ID60068
{
	public ArrayList<TreeNode> reverseBinaryTree(TreeNode root)
	{
		ArrayList<TreeNode> resultList=new ArrayList<TreeNode>();
		reverseBinaryTree(root, null, true, resultList);
		return resultList;
	}
	
	private void reverseBinaryTree(TreeNode root, TreeNode parentNode, boolean isLeft, ArrayList<TreeNode> resultList)
	{
		if (root==null)
			return;
		reverseBinaryTree(root.left, root, true, resultList);
		reverseBinaryTree(root.right, root, false, resultList);
		if (root.left==null && root.right==null)
			resultList.add(root);
		if (isLeft)
		{// originally this node is the left child of its parent node
			root.left=null;
			root.right=parentNode;
		}
		else
		{
			root.left=parentNode;
			root.right=null;
		}
	}
	
	public static void main(String[] args)
	{
		TreeNode root=new TreeNode(1);
		root.left=new TreeNode(2);
		root.right=new TreeNode(3);
		root.left.left=new TreeNode(4);
		root.left.right=new TreeNode(5);
		root.right.left=new TreeNode(6);
		root.right.right=new TreeNode(7);		
		
		System.out.println(root.toStringAll());
		
		ID60068 wpd=new ID60068();
		System.out.println(wpd.reverseBinaryTree(root));
	}

}

- wangpidong October 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You can use right root left to traverse in reverse order.

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

you can use right root left

- Vipul Vikram June 26, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

(1) go for simple inorder traversal
(2) make each node's(not the root) left pointer pointing to its parent
(3) whenever you get a leaf, add it to the linked list

- mail2vcp@gmail.com September 30, 2008 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nice solution. It can be improved if instead of always making the left pointer pointing to root.
We can use a variation as if a node is a left child of its parent then use the left pointer point to parent else use the right pointer to point to the parent. In this way we will be able to preserve information regarding the structure of the tree. and thus we can get back the original tree from its reverse.

- Sandeep6883@gmail.com November 24, 2008 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can somebody please depict, what do we mean by reversing a tree...pictorial or otherwise ? Does this mean mirroring the tree or is it the case of inverting the tree... I am aware of the mirroring technique, however how do you go about inverting a tree ? not sure if it is even possible ?

- amit January 03, 2012 | 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