Problem
Given a binary search tree with 2 nodes swapped find number of pairs not following BST properties
Follow up: Recover Binary Search Tree
Examples
Example 1
Consider the BST:
|
|
|
|
Solution
Method 1 - Inorder Traversal
We can have following solution:
- Find the inorder traversal of the input tree. Example - 2, 5, 20, 10, 8
- Find the number of inversions in the inorder traversal. That is the answer. Here the inversions are 20-10, 20-8, and 10-8.
Complexity
- Time:
O(n log n)
as O(n) time for inorder traversal and O(nlogn) for number of inversions in the sorted array. - Space:
O(1)