Fixed write tree bug.
Removed recursion in favor of stack.