题目描述:
二叉搜索树中的两个节点被错误地交换,请在不改变其结构的情况下,恢复这棵树。
-
示例 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
解一:
- 1、中序遍历
- 2、找出中序遍历结果中两个需要交换的值
- 3、重新遍历二叉树,将对应节点的val交换赋值
/**
* 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> list=new ArrayList<>();
getMid(root,list);
int[] arr=new int[2];
arr=getSwap(list);
swap(root,arr);
}
//中序遍历
public void getMid(TreeNode root,List<Integer> mid){
if(root==null){
return;
}
getMid(root.left,mid);
mid.add(root.val);
getMid(root.right,mid);
}
//中序遍历中两个需要交换的值
public int[] getSwap(List<Integer> mid){
int n=mid.size();
int x=-1,y=-1;
for(int i=0;i<n-1;i++){
if(mid.get(i+1)<mid.get(i)){
y=mid.get(i+1);
if(x==-1){
x=mid.get(i);
}else{
break;
}
}
}
return new int[]{x,y};
}
//交换赋值
public void swap(TreeNode root,int[] arr){
if(root==null){
return;
}
swap(root.left,arr);
if(root.val==arr[0]){
root.val=arr[1];
}else{
if(root.val==arr[1]){
root.val=arr[0];
}
}
swap(root.right,arr);
}
}
解二:递归交换
- 不需要中序遍历后寻找两个需要交换的值,而是递归中序遍历过程中找到需要交换的两个节点
/**
* 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 x;
TreeNode y;
TreeNode pre;
public void recoverTree(TreeNode root){
swapNode(root);
swap(x,y);
}
public void swapNode(TreeNode root) {
if(root==null){
return;
}
swapNode(root.left);
if(pre==null){
pre=root;
}else{
if(pre.val > root.val){
if(x==null){
x=pre;
y=root;
}else{
y=root;
}
}
}
pre=root;
swapNode(root.right);
}
public void swap(TreeNode x,TreeNode y){
int tmp=x.val;
x.val=y.val;
y.val=tmp;
}
}
二叉搜索树(BST)
- 中序遍历结果为递增或递减
详细说明BST