Binary tree node shifting

Someone please explain the approach along with the code for the below question