LeetCode每日一题:修复二叉搜索树

问题描述

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

问题分析

我们注意到二叉搜索树的中序排列是一个递增的数,我们只要把他的中序上大小错误的点交换,重新改成中序排列的就行了

代码实现

public void recoverTree(TreeNode root) {
        ArrayList list = new ArrayList<>();
        getBSTNode(root, list);
        TreeNode mistake1 = null;
        TreeNode mistake2 = null;
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i).val > list.get(i + 1).val) {
                mistake1 = list.get(i);
                break;
            }
        }
        for (int i = list.size() - 1; i > 0; i--) {
            if (list.get(i).val < list.get(i - 1).val) {
                mistake2 = list.get(i);
                break;
            }
        }
        int temp = mistake1.val;
        mistake1.val = mistake2.val;
        mistake2.val = temp;
    }

    private void getBSTNode(TreeNode root, ArrayList list) {
        if (root != null) {
            getBSTNode(root.left, list);
            list.add(root);
            getBSTNode(root.right, list);
        }
    }

你可能感兴趣的:(LeetCode每日一题:修复二叉搜索树)