Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Binary Search Tree Operations: Trimming, Array Conversion, and Greater Sum Tree

Tech Sep 14 1

Trimming a Binary Search Tree (LeetCode 669)

The algorithm removes all nodes not within the range [low, high]. The key insight is the nested recursion: when the current node's value is outside the range, one entire subtree can be discarded, but the other subtree may still contain out-of-range nodes and must be recursively trimmed.

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if (root == nullptr) return nullptr;
        if (root->val < low) return trimBST(root->right, low, high);
        if (root->val > high) return trimBST(root->left, low, high);
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
    }
};

Explanation: If root->val < low, the entire left subtree (including root) is eliminated; only the right subtree might have valid nodes. Similarly for root->val > high. When the root is in range, we recursively trim both children.

Converting Sorted Array to Height-Balanced BST (LeetCode 108)

A height-balanced BST minimizes depth. With a sorted array, the middle element becomes the root, and the left and right halves recursively form the left and right subtrees.

class Solution {
private:
    TreeNode* build(vector<int>& nums, int left, int right) {
        if (left > right) return nullptr;
        int mid = left + (right - left) / 2;
        TreeNode* node = new TreeNode(nums[mid]);
        node->left = build(nums, left, mid - 1);
        node->right = build(nums, mid + 1, right);
        return node;
    }
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return build(nums, 0, nums.size() - 1);
    }
};

Explanation: Using inclusive indices simplifies the recursion. The mid calculation avoids overflow. Each recursive call handles a contiguous subarray.

Converting BST to Greater Sum Tree (LeetCode 538)

A Greater Sum Tree replaces each node's value with the sum of all nodes greater than or equal to it in the original BST. This requires a reverse in-order traversal (right → root → left), accumulating values from the largest downwards.

class Solution {
private:
    int accum = 0;
    TreeNode* traverse(TreeNode* root) {
        if (root == nullptr) return nullptr;
        root->right = traverse(root->right);
        root->val += accum;
        accum = root->val;
        root->left = traverse(root->left);
        return root;
    }
public:
    TreeNode* convertBST(TreeNode* root) {
        return traverse(root);
    }
};

Explanation: accum tracks the running sum of all visited nodes (which are larger due to reverse order). For each node, we add the current accum, then update accum to include this node's new value. The traversal returns the (modified) root, allowing chaining.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.