Given any binary tree, what is the maximum number of turns possible in any path from root to any leaf?
A turn is when the path involves moving from left branch to right or vice-versa; i.e. the number of angels in a path. A straight line path has no turns.
The best I could get is the code below and it works with good performance, looking for better implementation
public class Tree
{
public int x;
public Tree l;
public Tree r;
}
private int leftTurns(Tree T, int turns)
{
if (T == null)
return 0;
return turns += Math.Max(
leftTurns(T.l, 0),
rightTurns(T.r, 1));
}
private int rightTurns(Tree T, int turns)
{
if (T == null)
return 0;
return turns += Math.Max(
leftTurns(T.l, 1),
rightTurns(T.r, 0));
}
public int solution(Tree T)
{
// write your code in C# 6.0 with .NET 4.5 (Mono)
return Math.Max(
leftTurns(T.l, 0),
rightTurns(T.r, 0));
}
My concerns:
- The semi-duplicate functions
leftTurns()
&rightTurns()
- The readability of the algorithm
- Is recursion necessary?