Google | Phone Interview | India | SWE
Anonymous User
2372

Given a tree, implement below mentioned two methods in the Solution class.

Structure of a tree node;

struct TreeNode
{
	const vector<TreeNode*> children;
};

Solution class

class Solution
{
private:


public:
	Solution(const TreeNode* root)
	{
	}
	
	// Q1. Implement GetParent method which takes in two nodes and return who is parent among those two
	// i.e. Either A is parent of B or B is parent of A or none of them are parent.
	TreeNode* GetParent(TreeNode* A, TreeNode* B)
	{
		// Returns among A or B, who is parent
		// This method is called multiple times
	}
	
	// Q2. Implement ChangeRoot method which takes in pointer to the new root and updates the mapping accordingly.
	void ChangeRoot(TreeNode* newRoot)
	{
		// Updates the root of the tree.
		// This method is called occassionly.
	}
}

Notes for Q2:

  1. An example to demonstrate what changing root means is shown below. To understand what is happening, imagine, all the nodes are connected via some kind of thread (parent - child relationship) and without breaking any thread you pull the root to the top.

    		 1
    	 /   |   \
    	2    3    4
      / | \   
    5   6   7
    	| \
    	8   9 

    Update root with 6

    		 6
    	 /   |   \
    	2    8    9
      / | \   
     5  7   1
    		| \
    		3  4

Hope this helps.

EDIT #1: Question #2 is not a simple problem. The child-parent relationship is constant and because of that you cannot update the tree structure. The Solution class is to behave as such that after calling the update root method, the root has been updated but the original tree structure is maintained. Please refer to the example mentioned above to understand what "updating" root means.

Comments (6)