




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.
1#include <stdio.h>
2#include <stdlib.h>
3typedef struct TreeNode {
4    int val;
5    struct TreeNode *left;
6    struct TreeNode *right;
7} TreeNode;
8void inorder(TreeNode* node, TreeNode** nodes, int* index) {
9    if (!node) return;
10    inorder(node->left, nodes, index);
11    nodes[(*index)++] = node;
12    inorder(node->right, nodes, index);
13}
14void recoverTree(TreeNode* root) {
15    TreeNode* nodes[1000];
16    int index = 0;
17    inorder(root, nodes, &index);
18    TreeNode *x = NULL, *y = NULL;
19    for (int i = 1; i < index; ++i) {
20        if (nodes[i]->val < nodes[i-1]->val) {
21            y = nodes[i];
22            if (!x) x = nodes[i - 1];
23            else break;
24        }
25    }
26    int temp = x->val;
27    x->val = y->val;
28    y->val = temp;
29}Here, we use an array to store nodes during an in-order traversal similar to our prior implementations. The array helps keep track of nodes' order, finding the pair of misplaced nodes efficiently and subsequently swapping their values to sort the array.
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).
1This 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.