Recover Binary Search Tree

I am not able to solve this question. Please help.

Approach

Here is the algorithm:

  1. Construct inorder traversal of the tree. It should be an almost sorted list where only two elements are swapped.
  2. Identify two swapped elements x and y in an almost sorted array in linear time.
  3. Traverse the tree again. Change value x to y and value y to x.

Complexity Analysis :

  • Time complexity : O(N). To compute inorder traversal takes O(N) time, to identify and to swap back swapped nodes O(1) in the best case and O(N) in the worst.
  • Space complexity : O(N) since we keep inorder traversal nums with N elements.

refer this --> https://ide.codingblocks.com/s/636876

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.