99 Recover Binary Search Tree

99. Recover Binary Search Tree

1. Question

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?

2. Implementation

(1) Iteration

class Solution {
    public void recoverTree(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curNode = root;
        TreeNode preNode = null, firstNode = null, secondNode = null;

        while (curNode != null || !stack.isEmpty()) {
            if (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            else {
                curNode = stack.pop();
                if (preNode != null && preNode.val > curNode.val) {
                    if (firstNode == null) {
                        firstNode = preNode;
                    }
                    secondNode = curNode;
                }
                preNode = curNode;
                curNode = curNode.right;
            }
        } 

        if (firstNode != null && secondNode != null) {
            int temp = firstNode.val;
            firstNode.val = secondNode.val;
            secondNode.val = temp;
        }
    }
}

(2) Recursion

3. Time & Space Complexity

Iteration: 时间复杂度: O(n), 空间复杂度: O(h)

Recursion: 时间复杂度: O(n), 空间复杂度: O(h)

Last updated

Was this helpful?