Description
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Examples
Example 1:
Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
Example 2:
Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
Constraints:
The number of nodes in the tree is in the range [2, 1000].
−
2
31
-2^{31}
−231 <= Node.val <=
2
31
−
1
2^{31} - 1
231−1
Follow up: A solution using O(n) space is pretty straight-forward. Could you devise a constant O(1) space solution?
思路
最开始的思路肯定就是我顺着来一遍,然后正确排序,再重新来一遍进行赋值。
后来看了下速度比较快的方法,还是要用递归,中间的循环体产生的原因应该是,题目中明确表明了只有2个元素有问题,那么也就是只有2个元素不满足 prev < current 的条件,那需要交换的就是第一个不满足条件的prev和第二个不满足条件的current
代码
/**
* 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) {
List<Integer> route = new ArrayList<>();
Stack<TreeNode> ts = new Stack();
TreeNode save = root;
while (true){
while (root != null){
ts.push(root);
root = root.left;
}
if (ts.size() == 0)
break;
root = ts.pop();
route.add(root.val);
root = root.right;
}
Collections.sort(route);
root = save;
int i = 0;
while (true) {
while (save != null) {
ts.push(save);
save = save.left;
}
if (ts.size() == 0)
return;
save = ts.pop();
save.val = route.get(i);
i++;
save = save.right;
}
}
}
/**
* 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 {
TreeNode prev = new TreeNode((int) Double.NEGATIVE_INFINITY);
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
inorder(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}
public void inorder(TreeNode root){
if(root==null)
return;
inorder(root.left);
if(first == null && prev.val > root.val)
first = prev;
if(first != null && prev.val > root.val)
second = root;
prev = root;
inorder(root.right);
}
}