Answer
The solution, while being extremely simple, sometimes confuses many people because of the necessity of maintaining an array index for the next element. It can be solved with a simple recursion:
The solution, while being extremely simple, sometimes confuses many people because of the necessity of maintaining an array index for the next element. It can be solved with a simple recursion:
private static int FlattenTreeIntoArray(Node tree, int[] array, int i)
{
if (tree == null) return i; // Flatten left subtree
i = FlattenTreeIntoArray(tree.Left, array, i); // Get data from the current node
array[i] = tree.Data; // Flatten right subtree
i = FlattenTreeIntoArray(tree.Right, array, i + 1);
return i;
}