99. Recover Binary Search Tree
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
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
Approach
- 题目大意二叉搜索树中有两个元素位置错误,需要你将它们重新交换回去,并不破坏原先的结构。这道题不难,二叉搜索数有一个性质就是中序即升序,那么你只要遍历升序的时候找到两个异常的元素结点即可。
Code
class Solution {
public:
TreeNode* lastNode;
TreeNode* firstNode;
TreeNode* secondNode;
void inorderTraval(TreeNode* root) {
if (root == nullptr)return;
inorderTraval(root->left);
if (lastNode != nullptr&&firstNode == nullptr&&lastNode->val >= root->val)
firstNode = lastNode;
if (lastNode != nullptr&&firstNode != nullptr&&lastNode->val >= root->val)
secondNode = root;
lastNode = root;
inorderTraval(root->right);
}
void recoverTree(TreeNode* root) {
inorderTraval(root);
swap(firstNode->val, secondNode->val);
}
};