LinkedIn | Generate a binary tree from parent->child relationship
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2016-06-26Added By Anonymous
Source: Link
This was asked in LinkedIn Interview
Given a list of child->parent relationships, build a binary tree out of it. All the element Ids inside the tree are unique.
Example:
Given the following relationships:
Child Parent IsLeft
15 20 true
19 80 true
17 20 false
16 80 false
80 50 false
50 null false
20 50 true
You should return the following tree:
1 50
2 / \
3 20 80
4 / \ / \
515 17 19 16Function Signature
1/**
2 * Represents a pair relation between one parent node and one child node inside a binary tree
3 * If the _parent is null, it represents the ROOT node
4 */
5class Relation {
6 int parent;
7 int child;
8 bool isLeft;
9};
10
11
12/**
13 * Represents a single Node inside a binary tree
14 */
15class Node {
16 int id;
17 Node * left;
18 Node * right;
19}
20
21/**
22 * Implement a method to build a tree from a list of parent-child relationships
23 * And return the root Node of the tree
24 */
25Node * buildTree (vector<Relation> & data)
26{
27}