题目描述: 二叉搜索树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。1
示例 1:
输入: [1,3,null,null,2]
1
/
3
\
2
输出: [3,1,null,null,2]
3
/
1
\
2
- 分析: 分为三步
- 二叉搜索树的中序遍历是递增数列,先将二叉树进行中序遍历
- 找到被错误交换的两个结点值,
- 交换两个结点值
- 代码:
private List<Integer> l;
public void recoverTree(TreeNode root) {
if(root == null) return;
l = new ArrayList<>();
//中序遍历
order(root);
//获取交换的节点坐标
int[] indexs = findIndex();
int first = l.get(indexs[0]);
int second = l.get(indexs[1]);
//交换两个值
swap(root,first,second);
}
public void order(TreeNode root){
if(root == null) return;
order(root.left);
l.add(root.val);
order(root.right);
}
public int[] findIndex(){
int size = l.size();
int[] res = {-1,-1};
for(int i = 0;i<size;i++){
// cur = l.get(i);
if(isValid(i)){
if(res[0] == -1) res[0] = i;
else res[1] = i;
}
}
if(res[1] == -1) res[1] = res[0];
return res;
}
public boolean isValid(int index){
int s = l.size();
if(index == 0 && index+1 < s && l.get(index) > l.get(index + 1)){
return true;
}else if(index == s - 1 && index-1>=0 && l.get(index) < l.get(index - 1)){
return true;
}else{
if(index + 1 < s && index - 1 >= 0 &&
(l.get(index) > l.get(index + 1) || l.get(index) < l.get(index - 1))){
return true;
}
}
return false;
}
public void swap(TreeNode root ,int first,int second){
if(root == null) return;
if(root.val == first) root.val = second;
else if(root.val == second) root.val = first;
swap(root.left,first,second);
swap(root.right,first,second);
}
https://leetcode-cn.com/problems/recover-binary-search-tree ↩︎