难度:Hard
原题连接
内容描述
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);
}
};