




Sponsored
Sponsored
This approach uses an additional list to store the nodes during an in-order traversal of the BST. The in-order traversal yields the values of the BST in a sorted manner for a correct BST configuration. If two nodes have been swapped, this sorted order will be violated in exactly two places. By storing all nodes during traversal and comparing them, we can identify the two swapped nodes. Once identified, we swap their values to correct the tree.
This method requires O(n) space to store the nodes' values where n is the number of nodes in the tree.
Time Complexity: O(n) since we are conducting an in-order traversal of the tree.
Space Complexity: O(n) as we store nodes in a list for comparison.
1import java.util.*;
2class Solution {
3    public void recoverTree(TreeNode root) {
4        List<TreeNode> nodes = new ArrayList<>();
5        inorder(root, nodes);
6        TreeNode x = null, y = null;
7        for (int i = 1; i < nodes.size(); i++) {
8            if (nodes.get(i).val < nodes.get(i - 1).val) {
9                y = nodes.get(i);
10                if (x == null) {
11                    x = nodes.get(i - 1);
12                } else break;
13            }
14        }
15        int temp = x.val;
16        x.val = y.val;
17        y.val = temp;
18    }
19    private void inorder(TreeNode node, List<TreeNode> nodes) {
20        if (node == null) return;
21        inorder(node.left, nodes);
22        nodes.add(node);
23        inorder(node.right, nodes);
24    }
25}This Java solution follows a similar logic of in-order traversal with storage. Nodes are stored in a list and then checked for swapped nodes based on the order of node values. Identified nodes are then corrected by swapping their values.
This approach leverages Morris Traversal to achieve O(1) space complexity, without needing an auxiliary stack or recursion. Morris Traversal utilizes the tree structure itself to keep track of nodes and ensures the tree is reset to its original configuration after traversal. To correct the BST, we detect swapped nodes by identifying violation of BST properties during traversal, and then we swap these nodes to achieve a valid BST.
Time Complexity: O(n).
Space Complexity: O(1).
This Java solution implements Morris Traversal by utilizing the BST's structure to achieve efficient traversal without extra space. Temporary links are created, helping in 'inorder' processing and swapping any disorderly node values.