Leetcode刷题——99

99. Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

二叉树的中序遍历数组是递增的

所以首先对二叉树进行中序遍历,得到递增数组,如果数组中有不是递增的数对,则将不递增的数对进行交互位置保证数组整体递增即可。

对于不是递增的情况有两种(因为题目中给出仅有两个元素位置错位)。

  • 整个数组中只有一对非递增数对:仅将这个数对的两个元素位置对换即可
  • 整个数组中有两对非递增数对:例如存在 x i > x i + 1 , x j > x j + 1 x_i > x_{i+1}, x_j > x_{j+1} xi>xi+1,xj>xj+1,只需要对换 x i x_i xi x j + 1 x_{j+1} xj+1 的位置即可
/**
 * 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<Integer> nums = new ArrayList<>();
        inordersearch(root, nums);
        int[] change = getchange(nums);
        changeTree(root, change);
    }

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

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

        return new int[]{x, y};
    }

    public void changeTree(TreeNode root, int[] change){
        if(root == null){
            return;
        }

        if(root.val == change[0]){
            root.val = change[1];
        }else if(root.val == change[1]){
            root.val = change[0];
        }

        changeTree(root.left, change);
        changeTree(root.right, change);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值