1. Collect Valid Nodes & Reconstruct BST
Intuition
Perform an inorder traversal, filter elements between low and high, and construct a new BST. While all values are in range, this modifies tree topology and allocates O(N) memory, failing strict LeetCode structural validation.
When to apply: Baseline comparison (note: violates the relative structure preservation requirement).
Algorithm
- Collect all elements in range [low, high] into an array, and rebuild a balanced BST.
#include <iostream>#include <vector> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { void inorder(TreeNode* root, int low, int high, std::vector<int>& vals) { if (!root) return; inorder(root->left, low, high, vals); if (root->val >= low && root->val <= high) vals.push_back(root->val); inorder(root->right, low, high, vals); } TreeNode* build(const std::vector<int>& vals, int l, int r) { if (l > r) return nullptr; int mid = l + (r - l) / 2; TreeNode* node = new TreeNode(vals[mid]); node->left = build(vals, l, mid - 1); node->right = build(vals, mid + 1, r); return node; }public: TreeNode* trimBST(TreeNode* root, int low, int high) { std::vector<int> vals; inorder(root, low, high, vals); return build(vals, 0, (int)vals.size() - 1); }}; int main() { TreeNode* root = new TreeNode(3); root->left = new TreeNode(0); root->right = new TreeNode(4); root->left->right = new TreeNode(2); root->left->right->left = new TreeNode(1); Solution sol; TreeNode* res = sol.trimBST(root, 1, 3); std::cout << "Root: " << res->val << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)