LeetCode刷题实战99:恢复二叉搜索树
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 恢复二叉搜索树,我们先来看题面:
https://leetcode-cn.com/problems/recover-binary-search-tree/
You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
题意
解题
public class Solution {
Listlist;
public void recoverTree(TreeNode root) {
list = new ArrayList<>();
inorderTraversal(root);
ListtempList = new ArrayList<>(list);
Collections.sort(tempList, new Comparator() {
@Override
public int compare(TreeNode treeNode1, TreeNode treeNode2) {
return treeNode1.val - treeNode2.val;
}
});
ListwrongList = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
if(list.get(i).val != tempList.get(i).val){
wrongList.add(i);
}
}
change(list, wrongList.get(0), wrongList.get(1));
}
private void inorderTraversal(TreeNode root){
if(root == null){
return;
}
inorderTraversal(root.left);
list.add(root);
inorderTraversal(root.right);
}
private void change(Listlist, int i, int j) {
Integer temp = list.get(i).val;
list.get(i).val = list.get(j).val;
list.get(j).val = temp;
}
}
上期推文: