leetcode **99. 恢复二叉搜索树(待深究)

【题目】**99. 恢复二叉搜索树

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

示例 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
进阶:

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

【解题思路1】显示中序遍历

找到二叉搜索树中序遍历得到值序列的不满足条件的位置。
如果有两个,记为 i 和 j(i<j 且 ai>ai+1 && aj>aj+1,对应被错误交换的节点即为 ai 对应的节点和 aj+1对应的节点,分别记为 x 和 y。
如果有一个,记为 i,那么对应被错误交换的节点即为 ai 对应的节点和 ai+1对应的节点,我们分别记为 x 和 y。
交换 x 和 y 两个节点即可。
开辟一个新数组 nums 来记录中序遍历得到的值序列,然后线性遍历找到两个位置 i 和 j,并重新遍历原二叉搜索树修改对应节点的值完成修复,具体实现可以看下面的代码。

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);
        }
    }
}

【解题思路2】


猜你喜欢

转载自blog.csdn.net/XunCiy/article/details/107874960
今日推荐