99. Recover Binary Search Tree
难度:Hard
刷题内容
原题连接
- https://leetcode.com/problems/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
˼· **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(1)***
�������Ҫ�㶮ƽ内容描述内容描述ʱ�����ġ内容描述��ʺ�����ֻ��Ҫ�Զ内容描述内容描述���ҵ��ĸ内容描述���ɣ������һ内容描述�����֮��Ϊ 321������3��1���ڶ内容描述������֮��Ϊ 1324������3��2��
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* n1;
TreeNode* n2;
TreeNode* pre = new TreeNode(INT_MIN);
void travel(TreeNode* root){
if(!root)
return;
travel(root ->left);
if(!n1 && root ->val <= pre ->val)
n1 = pre;
if(pre && n1 && root ->val <= pre ->val)
n2 = root;
pre = root;
travel(root ->right);
}
void recoverTree(TreeNode* root) {
travel(root);
swap(n1 ->val,n2 ->val);
}
};