Facebook Interview Question for SDE1s


Country: United States




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

Since it's not a regular binary tree, but a binary search tree, and taking in account that parent 1 and 2 are not ancestors (meaning that the parents are located in two different subtrees), having 2 parents breaks the property of a binary search tree. So, we can just check if the child's value satisfies the property or not.
In the code below, I assume that in the BST, left child's value must be less, and the right child's value must be greater or equal to the value of the parent.

#include <iostream>

using namespace std;

class Node {
	public:
		Node(int val)
		{
			val_ = val;
			left_ = right_ = NULL;
		}
		int val_;
		Node *left_, *right_;
};

void FixBst(Node *n, int upper = numeric_limits<int>::max(), int lower = numeric_limits<int>::min(), Node *parent = NULL)
{
	if (n) {
		if (parent) {
			if (n->val_ < lower ||
				n->val_ >= upper)
			{
				cout << parent->val_ << "->" << n->val_ << "\n";
				if (parent->left_ == n) {
					parent->left_ = NULL;
				} else {
					parent->right_ = NULL;
				}
			}
		}
		FixBst(n->left_, min(upper, n->val_), lower, n);
		FixBst(n->right_, upper, max(lower, n->val_), n);
	}
}

int main()
{
/*
      (7)
      / \
    (5) (9)
      \ /
      (6)
*/
	Node n1(7), n2(5), n3(9), n4(6);
	n1.left_ = &n2;
	n1.right_ = &n3;
	n2.right_ = &n4;
	n3.left_ = &n4;

	FixBst(&n1);
	return 0;
}

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

We use BFS to traverse the tree while keeping track on each child's parent
The same can be coded using recursion. As the question stated: this method fixes only one broken node (it can be adjusted to continue and scan for more double links):

#include "CommonHeader.h"

class BSTNode
{
public:
    std::string label;
    std::vector<BSTNode*> children;
    BSTNode(const std::string& n)
        : label(n)
    {
    }
    BSTNode() {}
};

static std::unordered_map<std::string, BSTNode> G;
// Our test tree
//                           (a)
//                           / \ 
//                          /   \ 
//                         (b) (c)
//                         |   /
//                         |  /
//                         (d)
BSTNode* makeTestTree()
{
    G["a"] = BSTNode("a");
    G["b"] = BSTNode("b");
    G["c"] = BSTNode("c");
    G["d"] = BSTNode("d");

    G["a"].children.push_back(&G["b"]);
    G["a"].children.push_back(&G["c"]);
    G["c"].children.push_back(&G["d"]); // double parent
    G["b"].children.push_back(&G["d"]); // double parent
    return &G["a"];
}

void fixDoubleParentNode()
{
    BSTNode* bst = makeTestTree();
    
    // Keep track of the parents
    std::unordered_map<BSTNode*, BSTNode*> Parents;
    
    // Use BFS with Queue (we can apply the same logic with recursion)
    std::queue<BSTNode*> q;
    q.push(bst);
    Parents[bst] = nullptr;
    while(!q.empty()) {
        BSTNode* node = q.front();
        q.pop();

        for(size_t i = 0; i < node->children.size(); ++i) {
            BSTNode* child = node->children[i];
            if(Parents.count(child)) {
                // already visited this child
                node->children.erase(node->children.begin() + i);
                std::cout << "Found duplicate parenting for node: " << child->label
                          << " faulty parent: " << node->label << " is removed" << std::endl;
                return;
            } else {
                Parents[child] = node;
                q.push(child);
            }
        }
    }
}

- PenChief October 02, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FixBst
{
	public static void main(String args[])
	{
		TreeNode root= new TreeNode(3);
		root.left = new TreeNode(1);
		root.right = new TreeNode(6);
		root.left.right = new TreeNode(2);
		root.right.left = root.left.right;

		FixBst f = new FixBst();
		f.print(root);
		f.fix(root, Integer.MIN_VALUE, Integer.MAX_VALUE, null);
		System.out.println();
		f.print(root);

	}

	public void fix(TreeNode root, int min, int max, TreeNode parent)
	{
		if(root==null)
			return;
		if(root.val > min && root.val <= max)
		{
			fix(root.left, min, root.val, root);
			fix(root.right, root.val, max, root);
		}
		else
		{
			if(parent.left.val == root.val)
				parent.left = null;
			else if(parent.right.val == root.val)
				parent.right = null;
		}
	} 

	private void print(TreeNode root)
	{
		if(root==null)
			return;

		print(root.left);
		System.out.print(root.val+"\t");
		print(root.right);
	}
}

class TreeNode
{
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int val)
	{
		this.val = val;
	}
}

- noob October 17, 2017 | 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