99. 恢复二叉搜索树

316 阅读2分钟

题目介绍

力扣99题:leetcode-cn.com/problems/re…

image.png

image.png

方法一

我们需要考虑两个节点被错误地交换后对原二叉搜索树造成了什么影响。对于二叉搜索树,我们知道如果对其进行中序遍历,得到的值序列是递增有序的,而如果我们错误地交换了两个节点,等价于在这个值序列中交换了两个值,破坏了值序列的递增性。

我们来看下如果在一个递增的序列中交换两个值会造成什么影响。假设有一个递增序列 a=[1,2,3,4,5,6,7]a=[1,2,3,4,5,6,7]。如果我们交换两个不相邻的数字,例如 22 和 66,原序列变成了 a=[1,6,3,4,5,2,7]a=[1,6,3,4,5,2,7],那么显然序列中有两个位置不满足 a[i] < a[i+1],在这个序列中体现为 6>36>3,5>25>2,因此只要我们找到这两个位置,即可找到被错误交换的两个节点。

至此,解题方法已经呼之欲出了:

    1. 找到二叉搜索树中序遍历得到值序列的不满足条件的位置。
    1. 交换这两个位置的节点数值就可。

代码如下:

class Solution {
    public void recoverTree(TreeNode root) {
        List<Integer> nums = new ArrayList<Integer>();
        inorder(root, nums);
        int[] swapped = findTwoSwapped(nums);
        recover(root, 2, swapped[0], swapped[1]);
    }

    public void inorder(TreeNode root, List<Integer> nums) {
        if (root == null) {
            return;
        }
        inorder(root.left, nums);
        nums.add(root.val);
        inorder(root.right, nums);
    }

    public int[] findTwoSwapped(List<Integer> nums) {
        int n = nums.size();
        int x = -1, y = -1;
        for (int i = 0; i < n - 1; ++i) {
            if (nums.get(i + 1) < nums.get(i)) {
                y = nums.get(i + 1);
                if (x == -1) {
                    x = nums.get(i);
                } else {
                    break;
                }
            }
        }
        return new int[]{x, y};
    }

    public void recover(TreeNode root, int count, int x, int y) {
        if (root != null) {
            if (root.val == x || root.val == y) {
                root.val = root.val == x ? y : x;
                if (--count == 0) {
                    return;
                }
            }
            recover(root.right, count, x, y);
            recover(root.left, count, x, y);
        }
    }
}

复杂度分析

  • 时间复杂度:O(N),其中 NN 为二叉搜索树的节点数。中序遍历需要 O(N)的时间,判断两个交换节点在最好的情况下是 O(1),在最坏的情况下是 O(N) ,因此总时间复杂度为 O(N)。
  • 空间复杂度:O(N)。我们需要用nums 数组存储树的中序遍历列表。

方法二

方法一的空间复杂度较高,其实找到需要交换的两个节点不用那么麻烦,我们可以根据题意分析只需要中序遍历找到,第一个升序顺序错乱最大值节点,和最后一个升序顺序错乱的最小值节点。然后交换两个节点val即可。

代码如下:

class Solution {
    //第一个最大值节点
    TreeNode firstMax=null;
	//最后一个最小值节点
    TreeNode lastMin=null;
	//前一个节点
    TreeNode prev=new TreeNode(Integer.MIN_VALUE);
    public void recoverTree(TreeNode root){
        helper(root);
        if(firstMax!=null && lastMin!=null){
            int tmp=firstMax.val;
            firstMax.val=lastMin.val;
            lastMin.val=tmp;
        }
    }
    public void helper(TreeNode root){
        if(null==root)return;
        helper(root.left);
        if(root.val<prev.val) {
            lastMin=root;
            if(firstMax==null)firstMax=prev;
        }
        prev=root;
        helper(root.right);
    }
}

复杂度分析

  • 时间复杂度:O(N).
  • 空间复杂度:O(H),H为二叉树的高度。