Facebook Interview Question for Software Engineer / Developers


Team: Backend systems
Country: United States
Interview Type: Phone Interview




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

void Util::PrintLayers(BTree* RootNode)
{
queue<BTree*> myqueue;
myqueue.push(RootNode);
BTree* tempNode = RootNode;
int OldLevel = 1;
int NewLevel = 0;
while(myqueue.size() != 0)
{
tempNode = myqueue.front();


cout<<"\t"<<tempNode->Value;
if(tempNode->Left != 0)
{
myqueue.push(tempNode->Left);
NewLevel++;
}
if(tempNode->Right != 0)
{
myqueue.push(tempNode->Right);
NewLevel++;
}
myqueue.pop();
OldLevel--;
if(OldLevel == 0)
{
OldLevel = NewLevel;
NewLevel = 0;
cout<<endl;
}
}

}

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

Obvious, u've added more levels

- javabean March 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void print_LL(Node* node){//written in c++

queue<Node*> curr;
if(node == NULL) return;
curr.push(node);

int k= curr.size();
while(!curr.empty()){
Node *node = curr.front();
cout<<node->data<<" ";
curr.pop();
k--;
if(node->left != NULL) curr.push(node->left);
if(node->right != NULL) curr.push(node->right);
if(k==0 && !curr.empty()) {k=curr.size(); cout<<endl;}
}
}

- Alex March 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

queue.push(head);
queue.push("<delimiter>");
while(queue.size != 0)
{
      elem = queue.pop();
      if( elem == "<delimiter>" && queue.size() != 0) {
               queue.push("<delimiter>");
               continue;
      }
     if(elem->left) queue.push(elem->left);
    if(elem->right) queue.push(elem->right);
}
if tree is as below:
              50
     30             60
20       40   55    70

then it will be as follows:
1) 50->"<delim>"
2) print 50, enque 30, 60, queue looks like "<delim>"->30->60
3) print "<delim>", enqueue "<delim>", queue looks like 30->60->"<delim>"
4) print 30, enqueue 20, 40 queue looks like 60->"<delim>"->20->40
5) print 60, enqueue 55, 70 queue looks like "<delim>"->20->40->55->70
6) print "<delim>", enqueue "<delim>" queue looks like 20->40->55->70->"<delim>"
7) since they are leaf nodes, we will just pop them off

so output is: 50, " ", 30,60, " ", 20,40,55,70, " "

- mbg July 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Pseudocode

printTreeLevels(Node n):
        nextLevel = []
        printLevel(nextLevel.add(n),0)

printLevel(Node[] nodes, int level):
        if(nodes == null || nodes.size == 0):
              return;
         print "Level : " + level;
         nextLevel = []
         for(Node n: nodes):
              print n.name;
              nextLevel.add(n.left) if n.left != null;
              nextLevel.add(n.right) if n.right != null
          print "\n"
          printLevel(nextLevel, level + 1)

- Ram August 21, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Your nickname is great! *rofl*

Okay this has gotten way uglier than I anticipated but except for the printTree function the code doesn't really matter...

#include <string>
#include <vector>
#include <functional>
#include <memory>

template<class TTree>
void printTree(
    TTree tree, 
    std::function<void (TTree, std::function<void (TTree)>)> enumChildren, 
    std::function<void(TTree)> printNode, 
    std::function<void()> printLevelSepa)
{
    std::vector<TTree> frontier;
    
    frontier.push_back(tree);
    frontier.push_back(nullptr);
    
    for(int i = 0; i < frontier.size(); i++)
    {
        auto current = frontier[i];
        
        if(current == nullptr)
        {
            printLevelSepa();
            
            if(i < frontier.size() - 1) // only if there are children left to process
                frontier.push_back(nullptr); // signal end of next tree level
        }
        else
        {
            printNode(current);
            enumChildren(current, [&](TTree child) { frontier.push_back(child); }); 
        }
    }
}


class BinaryTree
{
public:
    typedef std::shared_ptr<BinaryTree> pointer_type;

    pointer_type left;  
    pointer_type right;
    std::string value;

    BinaryTree(std::string value) : value(value), left(nullptr), right(nullptr) { }
    BinaryTree(std::string value, pointer_type left, pointer_type right) : value(value), left(left), right(right) { }
};

int main(int argc, char** argv)
{
    auto tree = std::make_shared<BinaryTree>(
            "Root",
            std::make_shared<BinaryTree>(
                "L1_left",
                std::make_shared<BinaryTree>("L1L_left"),
                std::make_shared<BinaryTree>("L1R_right")
            ),
            std::make_shared<BinaryTree>(
                "R1_right",
                std::make_shared<BinaryTree>("R1L_left"),
                std::make_shared<BinaryTree>("R1R_right")
            )
        );

    printTree<BinaryTree::pointer_type>(
        tree,
        [&](BinaryTree::pointer_type node, std::function<void (BinaryTree::pointer_type)> callback) 
        {
            if(node->left != nullptr) callback(node->left);
            if(node->right != nullptr) callback(node->right);
        },
        [&](BinaryTree::pointer_type node) { std::cout << node->value << " "; },
        [&]() { std::cout << std::endl; });


    return 0;
}

- FBNerd February 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void PrintTreeLevelOrderQueue(TreeNode root)
        {
            var q = new Queue<TreeNode>();
            q.Enqueue(root);
            var currentCount = 1;
            var nextCount = 0;
            while(q.Count > 0)
            {
                var currentNode = q.Dequeue();
                Console.Write(currentNode.Value + " ");
                currentCount -= 1;
                if (currentNode.Left != null)
                {
                    q.Enqueue(currentNode.Left);
                    nextCount += 1;
                }
                if (currentNode.Right != null)
                {
                    q.Enqueue(currentNode.Right);
                    nextCount += 1;
                }
                if(currentCount == 0)
                {
                    Console.WriteLine();
                    currentCount = nextCount;
                    nextCount = 0;
                }
            }
        }

- gmelshall April 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

LevelPrint(node* T )
{
 if( T==NULL )return;
 queue<node*>Q ;
 Q.enqueue(T);
 Q.enqueue(NULL); 
 while(!Q.empty())
 {
       node* t = Q.dequeue();
       if( t!=NULL )
       {
           if(t->left)
           Q.enqueue(t->left);
           
           if(t->right)
           Q.enqueue(t->right);
           
           print(t);
       }
       else
       {
           Q.enqueue(NULL);
       }
 }
              
}

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

In else block, I think you need to print newline as well.

- gimli February 20, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This code will never end. You need to ensure that you do not add any more NULLs to the queue once all nodes have been traversed.

- Anony March 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You can track how many nodes you've printed per level, resetting at the delimiter. If you hit a null without having processed anything at that level, then you're done.

- jon April 06, 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