99. Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:

A solution using O(

n

) space is pretty straight forward. Could you devise a constant space solution?

tag: binary search tree, in order traversal

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode first = null, second = null;
    TreeNode prev = new TreeNode(Integer.MIN_VALUE);

    public void recoverTree(TreeNode root) {

        dfs(root);

        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }

    private void dfs(TreeNode root){
        if (root == null) return;

        dfs(root.left);
        if (first == null && prev.val >= root.val) first = prev;
        if (first != null && prev.val >= root.val) second = root;
        prev = root;
        dfs(root.right);
    }
}

results for ""

    No results matching ""