Updated code to take care of maximum depth