I'm currently running through some Cracking the Coding Interview questions and my solution to 4-4 is quite different from any of the given solutions.
The question asks to determine if a given binary tree is balanced; more specifically, if the difference between the maximum and minimum depths within the tree is less than or equal to 1.
public static bool IsBalanced(Node node)
{
var mm = new DepthMinMax();
mm.Min = int.MaxValue;
mm.Max = int.MinValue;
FindMinMax(mm, node, 0);
return (mm.Max - mm.Min <= 1) ? true : false;
}
private static void FindMinMax(DepthMinMax mm, Node node, int depth)
{
if (node == null) return;
FindMinMax(mm, node.L, depth + 1);
FindMinMax(mm, node.R, depth + 1);
// At a terminating node
if (node.L == null || node.R == null)
{
if (mm.Min > depth) mm.Min = depth;
if (mm.Max < depth) mm.Max = depth;
}
}
public class Node
{
public Node L { get; set; }
public Node R { get; set; }
}
public class DepthMinMax
{
public int Min { get; set; }
public int Max { get; set; }
}
This works for my test cases, but they were far from exhaustive and I can't really conclude if my solution works for all cases / is efficient. My solution feels far too simple, which leads me to believe I've missed some kind of gotcha.