leetcode-99.-恢复二叉搜索树
描述
二叉搜索树中的两个节点被错误地交换。 请在不改变其结构的情况下,恢复这棵树。 示例 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 进阶:
解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void recoverTree(TreeNode root) {
List<Integer> nums = new ArrayList<>();
inOrder(root, nums);
int[] swaped = findTwoSwap(nums);
recover(root, 2, swaped[0], swaped[1]);
}
private void inOrder(TreeNode root, List<Integer> nums) {
if (root == null) {
return;
}
inOrder(root.left, nums);
nums.add(root.val);
inOrder(root.right, nums);
}
private int[] findTwoSwap(List<Integer> nums) {
int x = -1;
int y = -1;
for (int i = 0; i < nums.size() - 1; i++) {
if (nums.get(i+1) < nums.get(i)) {
y = nums.get(i+1) ;
if (x == -1) {
x = nums.get(i);
} else {
break;
}
}
}
return new int[] {x, y};
}
public void recover(TreeNode r, int count, int x, int y) {
if (count == 0) {
return;
}
if (r == null) {
return;
}
if (r.val == x || r.val == y) {
if (r.val == x) {
r.val = y;
} else if (r.val != x) {
r.val = x;
}
count--;
}
recover(r.left, count, x, y);
recover(r.right, count, x, y);
}
}
时间复杂度: N, 空间复杂度: N
参考: https://leetcode-cn.com/problems/validate-binary-search-tree/
浙公网安备 33010602011771号