Find the minimum number of switches to be turned on for illuminating the binary tree
algorithm
Solution
You can solve it recursively by considering what is the minimum number of switches that need to be turned on for each sub-tree, assuming the root node is on and also assuming it is off.
If the root node is on then the child nodes can be either on or off, so `minSwitchesAssumingRootOn` calls `minSwitches` recursively. If the root node is off then the child nodes must be on for the edges connected to the root node to be on, so `minSwitchesAssumingRootOff` calls `minSwitchesAssumingRootOn` recursively.
The sub-totals can be stored using memo-ization to speed it up. `tree.minAssumingOff` and `tree.minAssumingOn` should be initialized to -1.
Pseudo-code:
int minSwitches(tree)
{
if(tree == null)
return 0;
return min(minSwitchesAssumingRootOff(tree),
minSwitchesAssumingRootOn(tree));
}
int minSwitchesAssumingRootOn(tree)
{
if(tree == null)
return 0;
if(tree.minAssumingOn == -1)
tree.minAssumingOn = 1 + minSwitches(tree.left) + minSwitches(tree.right);
return tree.minAssumingOn;
}
int minSwitchesAssumingRootOff(tree)
{
if(tree == null)
return 0;
if(tree.minAssumingOff == -1)
tree.minAssumingOff = minSwitchesAssumingRootOn(tree.left) +
minSwitchesAssumingRootOn(tree.right);
return tree.minAssumingOff;
}
Problem
Consider a binary tree like: Think of the nodes as switches, which are initially `OFF` and the edges between nodes as tube lights (not glowing initially). When we switch on a particular node, then all the edges(tube lights) connected to that node glow. Find the minimum number of switches that need to be turned `ON` for the whole binary tree to glow. For example, if I switch on `2,3,4 and 9` or `2,3,8,9` then all the tube lights glow. So, the answer is `4` [see the diagram] I was asked about this question in an interview. Can anyone help me with the algorithm/pseudocode? No need for working code. For programmers and coders, think that the input is like: `n`: the number of edges given Then `n` lines follow in the form `x y` where `x` and `y` are two endpoints of the edge. According to the diagram above, the input will be: ``` 10 1 2 1 3 2 5 ... ``` Till now, I have figured out a few cases like: I never need to illuminate the leaf nodes Is a simple recursive solution present based on the above fact? Edit: Will the algorithm change if only the `Root` of the tree is given as `input` [Assume the tree is represented as a linked list] ??