Google | Phone Interview | India
Anonymous User
2755

Given a Binary Tree and a function predict. You need to call predict function for every node, if it returns true the node is marked deleted. You need to remove the nodes from the tree , which satisfies the either of below 2 conditions :
a) Node is marked deleted
b) Node's parent is not marked deleted
Return the list of remaining nodes in the Tree.
Complete this function -
prune(Node& root, std::function<bool(const Node&)> pred) {
bool flag = pred(root)
if(flag == true)
//remove root from tree
}

Ex-1 : deleted node according to predict function : 1
1
/ \ -> [2,3]
2 3

Ex-2 : deleted node according to predict function : 3,4
1
/ \ -> [1,5]
2 3
/
4 5

Solution-

  1. Do a traversal on tree and mark the deleted nodes.
  2. Do a level order traversal and check the condition. filter the nodes and return the list of undeleted nodes.

What's your thoughts?

Comments (10)