题目描述
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n ) space is pretty straight forward. Could you devise a constant space solution?
- 思路
二叉搜索树的两个节点发生了交换,恢复原来的结构。
法一:定义两个全局变量记录交换的两个节点,还有一个表示前一个的节点。然后中序遍历判断大小(交换的节点分为相邻的和不相邻的),找到交换的两个节点,最后交换它们的值。参考博客
法二:效率较低,中序遍历序列化此二叉树,然后排序。最后再中序遍历一遍赋对应的值。
//法一
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode mis1 = null;
TreeNode mis2 = null;
TreeNode pre = null;
public void recoverTree(TreeNode root) {
if(root == null)
return ;
getMistake(root);
if(mis1 != null && mis2 != null){
int t = mis1.val;
mis1.val = mis2.val;
mis2.val = t;
}
}
public void getMistake(TreeNode node){
if(node == null)
return ;
if(node.left != null)
getMistake(node.left);
if(pre != null && node.val < pre.val){
if(mis1 == null){
mis1 = pre;
mis2 = node; //交换的是相邻节点时
}else{
mis2 = node;
}
}
pre = node;
if(node.right != null)
getMistake(node.right);
}
}
//法二
import java.util.*;
public class Solution {
public void recoverTree(TreeNode root) {
if(root == null)
return ;
ArrayList<Integer> list = new ArrayList<Integer>();
inOrder(root, list);
Collections.sort(list);
inOrderInit(root, list);
}
public void inOrderInit(TreeNode node, ArrayList<Integer> list){
if(node != null){
inOrderInit(node.left, list);
node.val = list.get(0);
list.remove(0);
inOrderInit(node.right, list);
}
}
public void inOrder(TreeNode node, ArrayList<Integer> list){
if(node != null){
inOrder(node.left, list);
list.add(node.val);
inOrder(node.right, list);
}
}
}