leetcode【每日一题】. 恢复二叉搜索树 Java

题干

二叉搜索树中的两个节点被错误地交换。

请在不改变其结构的情况下,恢复这棵树。

示例 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) 空间复杂度的解法很容易实现。
你能想出一个只使用常数空间的解决方案吗?

想法

中序遍历
按理说应该是递增的
因为交换了
那么会有两个异常的点

如果两个交换的点是不相邻的,那么找出来,交换即可(通过中序遍历时前一个比后一个大,会有两个位置异常

如果两个交换点是相邻的,那么就只有一个位置异常,交换即可

Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void recoverTree(TreeNode root) {
        List<TreeNode> list=new ArrayList<>();
        inorder(root, list);
        int[] swapped = findTwoSwapped(list);
        recover(root, 2, swapped[0], swapped[1]);


    }

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

    }

    public int[] findTwoSwapped(List<TreeNode> list){
           int n=list.size();
           int x=-1,y=-1;
        for (int i = 0; i < n - 1; ++i) {
            if (list.get(i + 1).val < list.get(i).val) {
                y = list.get(i + 1).val;
                if (x == -1) {
                    x = list.get(i).val;
                } 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);
        }
    }
}

我的leetcode代码都已经上传到我的githttps://github.com/ragezor/leetcode

猜你喜欢

转载自blog.csdn.net/qq_43491066/article/details/107877194