Facebook | Phone | Minimum Edits for a Binary Tree
Anonymous User
11725

Given a binary tree, return the minimum number of edits to make the value of each node equal to the average of its direct children's. Note that you can only update the value of each tree node, and changing the tree structure is not allowed.

I was stuck at this question and couldn't find a recursive solution to it. Anyone has any clues?

Edit:

  1. "average of its direct children's" means the average of left and right children. If the left(right) children doesn't exist, then just let the root value equal to the value of its right(left) children. If the root is leaf, then the criteria is always met for this node.
  2. It doesn't matter if the value is int or float. We can use float.
  3. A tricky example:
    image

Edit2:
Here is another simple example that shows why this problem is extremely tricky..
image

The correct solution is 3, because we can either update the values of the three top nodes (with value=2) to "1", or update the vales of three bottom nodes (with value=1) nodes to "2".

However, if the bottom leaf doesn't exist, the only solution is to update the two bottom nodes and return 2. Similarly, if the current root doesn't exist (therefore the current root's right node is the new root), then the only solution is to update the two top nodes and return 2. So, looks like we have to see the whole picture before deciding whether to update the value of one node or not..

Comments (44)