二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
示例 1:
输入: [1,3,null,null,2]
1
/
3
2
输出: [3,1,null,null,2]
3
/
1
2
示例 2:
输入: [3,1,4,null,null,2]
3
/
1 4
/
2
输出: [2,1,4,null,null,3]
2
/
1 4
/
3
进阶:
使用 O(n) 空间复杂度的解法很容易实现。
你能想出一个只使用常数空间的解决方案吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/recover-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void recoverTree(TreeNode root) {
TreeNode x = null, y = null, pred = null, predecessor = null;
while(root != null){
if(root.left != null){//左子树不为空,就找左子树最右边的结点
predecessor = root.left;
while(predecessor.right != null && predecessor.right != root){
predecessor = predecessor.right;
}
if(predecessor.right == null){
predecessor.right = root;
root = root.left;
}
else{
if(pred != null && root.val < pred.val){
y = root;
if(x == null){
x = pred;
}
}
pred = root;
predecessor.right = null;
root = root.right;
}
}
else{
if(pred != null && root.val < pred.val){
y = root;
if(x == null){
x = pred;
}
}
pred = root;
root = root.right;
}
}
swap(x,y);
}
public void swap(TreeNode x, TreeNode y) {
int tmp = x.val;
x.val = y.val;
y.val = tmp;
}
}