Use depth-first tree iteration for better performance