




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 <vector>
2using namespace std;
3class Solution {
4public:
5    void recoverTree(TreeNode* root) {
6        vector<TreeNode*> nodes;
7        TreeNode *x = nullptr, *y = nullptr;
8        inorder(root, nodes);
9        for (int i = 1; i < nodes.size(); ++i) {
10            if (nodes[i]->val < nodes[i-1]->val) {
11                y = nodes[i];
12                if (x == nullptr) x = nodes[i - 1];
13                else break;
14            }
15        }
16        swap(x->val, y->val);
17    }
18    void inorder(TreeNode* node, vector<TreeNode*>& nodes) {
19        if (!node) return;
20        inorder(node->left, nodes);
21        nodes.push_back(node);
22        inorder(node->right, nodes);
23    }
24};In this C++ solution, we traverse the tree in an in-order manner and store each node in a vector. We then iterate through the vector to find the two swapped nodes by identifying the points where the currently observed order of the vector is decreased. These nodes are then swapped.
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).
JavaScript's handling of Morris Traversal assumes a pointer redirection to achieve O(1) space complexity while navigating the tree. Resultantly, node rearrangement fixes compounded node mismatches.