Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
Example 2:
Input: [3,1,4,null,null,2]
3
/ \
1 4
/
2
Output: [2,1,4,null,null,3]
2
/ \
1 4
/
3
解题思路分析:
- 这道题很容易想到的是使用中序遍历,把遍历结果保存起来,然后找到交换的两个结点,交换两个结点的值即可
- 难点问题在于如何找到交换的两个结点,有如下几种情况;(需要借助两个指针(first, second)分别指向交换的两个元素)
- 交换的结点相邻,例如:1,2,4,3,5,6
- 这种情况很简单,用两个指针直接指向这两个元素;
- 交换的结点不相邻,这里又可以分为两种情况
- 涉及三个结点,例如:1,2,
- 交换的结点相邻,例如:1,2,4,3,5,6