recusrive version replaced with iterative with stack