1. Two-Pass Inorder with Suffix Array
Intuition
Pass 1: Collect all nodes in a list using standard inorder traversal. Pass 2: Calculate suffix sums backwards. Pass 3: Overwrite each node's value with its corresponding suffix sum.
When to apply: Basic baseline before realizing the running sum can be maintained on-the-fly.
Algorithm
- Step 1: Traverse inorder, appending nodes to a list.
- Step 2: Compute running sum from right to left.
- Step 3: Assign
nodes[i].val = runningSum.
#include <iostream>#include <vector>using namespace std; struct TreeNode { int val; TreeNode *left, *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { void inorder(TreeNode* node, vector<TreeNode*>& nodes) { if (!node) return; inorder(node->left, nodes); nodes.push_back(node); inorder(node->right, nodes); }public: TreeNode* convertBST(TreeNode* root) { vector<TreeNode*> nodes; inorder(root, nodes); int sum = 0; for (int i = (int)nodes.size() - 1; i >= 0; i--) { sum += nodes[i]->val; nodes[i]->val = sum; } return root; }}; int main() { TreeNode* root = new TreeNode(4); root->left = new TreeNode(1); root->right = new TreeNode(6); Solution sol; sol.convertBST(root); cout << "Root: " << root->val << ", Left: " << root->left->val << ", Right: " << root->right->val << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)