首页   

​LeetCode刷题实战99:恢复二叉搜索树

程序IT圈  · 程序员  · 3 年前

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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?

题意


给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。

进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?

样例


解题


这题思路和LeetCode098——验证二叉搜索树中的思路二是一致的。

对于一棵二叉搜索树而言,其中序遍历的结果是一个递增序列。我们保存原二叉搜索树中序遍历的结果。再对该结果进行排序后得到另一个序列,比较两个序列中的不同的两个值,即为需要交换的两个错误节点。

时间复杂度是O(nlogn),其中n为树中的节点个数。空间复杂度也是O(n)。


public class Solution {
 
    List list;
 
    public void recoverTree(TreeNode root) {
        list = new ArrayList<>();
        inorderTraversal(root);
        List tempList = new ArrayList<>(list);
        Collections.sort(tempList, new Comparator() {
            @Override
            public int compare(TreeNode treeNode1, TreeNode treeNode2) {
                return treeNode1.val - treeNode2.val;
            }
        });
        List wrongList = 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(List list, int i, int j){
        Integer temp = list.get(i).val;
        list.get(i).val = list.get(j).val;
        list.get(j).val = temp;
    }
}


这道题,大家还有没有更好的解法呢?欢迎评论区讨论 。
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。


上期推文:

LeetCode50-80题汇总,速度收藏!
LeetCode刷题实战81:搜索旋转排序数组 II
LeetCode刷题实战82:删除排序链表中的重复元素 II
LeetCode刷题实战83:删除排序链表中的重复元素
LeetCode刷题实战84: 柱状图中最大的矩形
LeetCode刷题实战85:最大矩形
LeetCode刷题实战86:分隔链表
LeetCode刷题实战87:扰乱字符串
LeetCode刷题实战88:合并两个有序数组
LeetCode刷题实战89:格雷编码
LeetCode刷题实战90:子集 II
LeetCode刷题实战91:解码方法
LeetCode刷题实战92:反转链表 II
LeetCode刷题实战93:复原IP地址
LeetCode刷题实战94:二叉树的中序遍历
LeetCode刷题实战95:不同的二叉搜索树 II
LeetCode刷题实战96:不同的二叉搜索树
LeetCode刷题实战97:交错字符串
LeetCode刷题实战98:验证二叉搜索树

推荐文章
医学界  ·  “医生快来,患者心肌梗死了!”  ·  6 年前  
© 2022 51好读
删除内容请联系邮箱 2879853325@qq.com