1. Inorder Array Extraction + Re-sort
Intuition
Perform an inorder traversal, storing all node references in nodes and their values in vals. Sort vals. Iterate through nodes and assign nodes[i].val = vals[i]. Takes O(N log N) time and O(N) space.
When to apply: Baseline comparison when O(N) memory is unrestricted.
Algorithm
- Collect all node references and their values in arrays, sort the values, and rewrite values to nodes in-order.
#include <iostream>#include <vector>#include <algorithm> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { void inorder(TreeNode* root, std::vector<TreeNode*>& nodes, std::vector<int>& vals) { if (!root) return; inorder(root->left, nodes, vals); nodes.push_back(root); vals.push_back(root->val); inorder(root->right, nodes, vals); }public: void recoverTree(TreeNode* root) { std::vector<TreeNode*> nodes; std::vector<int> vals; inorder(root, nodes, vals); std::sort(vals.begin(), vals.end()); for (int i = 0; i < (int)nodes.size(); i++) { nodes[i]->val = vals[i]; } }}; int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(3); root->left->right = new TreeNode(2); Solution sol; sol.recoverTree(root); std::cout << "Root: " << root->val << " (Left: " << root->left->val << ")" << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N) - Space complexity:
O(N)