|
| 1 | +# [1038. Binary Search Tree to Greater Sum Tree](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Converting Binary Search Tree to Greater Sum Tree" |
| 6 | +summary: "An approach to solving the problem of converting a binary search tree to a greater sum tree using a reverse in-order traversal." |
| 7 | +date: "2024年06月25日" |
| 8 | +modified_date: "2024年06月25日" |
| 9 | +tags: ["binary search tree", "algorithm", "JavaScript", "tree traversal"] |
| 10 | +slug: "converting-bst-to-gst" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | +# Intuition |
| 15 | + |
| 16 | +The idea is to traverse the binary search tree (BST) in a way that allows us to accumulate the sum of all nodes greater than the current node. A reverse in-order traversal (right-root-left) will help in achieving this, as it processes the nodes in decreasing order. |
| 17 | + |
| 18 | +# Approach |
| 19 | + |
| 20 | +1. Initialize a variable `sum` to keep track of the accumulated sum of node values. |
| 21 | +2. Perform a reverse in-order traversal: |
| 22 | + - Traverse the right subtree. |
| 23 | + - Update the current node's value with the accumulated sum. |
| 24 | + - Traverse the left subtree. |
| 25 | +3. Return the modified tree. |
| 26 | + |
| 27 | +# Complexity |
| 28 | + |
| 29 | +- Time complexity: $$O(n)$$ because each node is visited exactly once. |
| 30 | + |
| 31 | +- Space complexity: $$O(h)$$, where $$h$$ is the height of the tree, due to the recursion stack. |
| 32 | + |
| 33 | +# Code |
| 34 | + |
| 35 | +```javascript |
| 36 | +/** |
| 37 | + * Definition for a binary tree node. |
| 38 | + * function TreeNode(val, left, right) { |
| 39 | + * this.val = (val===undefined ? 0 : val) |
| 40 | + * this.left = (left===undefined ? null : left) |
| 41 | + * this.right = (right===undefined ? null : right) |
| 42 | + * } |
| 43 | + */ |
| 44 | +/** |
| 45 | + * @param {TreeNode} root |
| 46 | + * @return {TreeNode} |
| 47 | + */ |
| 48 | +function bstToGst(root) { |
| 49 | + let sum = 0; |
| 50 | + |
| 51 | + function traverse(node) { |
| 52 | + if (!node) return; |
| 53 | + |
| 54 | + traverse(node.right); |
| 55 | + |
| 56 | + sum += node.val; |
| 57 | + node.val = sum; |
| 58 | + |
| 59 | + traverse(node.left); |
| 60 | + } |
| 61 | + |
| 62 | + traverse(root); |
| 63 | + return root; |
| 64 | +} |
| 65 | +``` |
0 commit comments