added logic to handle leaf nodes