File tree 2 files changed +41
-0
lines changed
2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 540
540
1023|[ Camelcase Matching] ( ./1023-camelcase-matching.js ) |Medium|
541
541
1028|[ Recover a Tree From Preorder Traversal] ( ./1028-recover-a-tree-from-preorder-traversal.js ) |Hard|
542
542
1037|[ Valid Boomerang] ( ./1037-valid-boomerang.js ) |Easy|
543
+ 1038|[ Binary Search Tree to Greater Sum Tree] ( ./1038-binary-search-tree-to-greater-sum-tree.js ) |Medium|
543
544
1041|[ Robot Bounded In Circle] ( ./1041-robot-bounded-in-circle.js ) |Medium|
544
545
1047|[ Remove All Adjacent Duplicates In String] ( ./1047-remove-all-adjacent-duplicates-in-string.js ) |Easy|
545
546
1051|[ Height Checker] ( ./1051-height-checker.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1038. Binary Search Tree to Greater Sum Tree
3
+ * https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every
7
+ * key of the original BST is changed to the original key plus the sum of all keys greater
8
+ * than the original key in BST.
9
+ *
10
+ * As a reminder, a binary search tree is a tree that satisfies these constraints:
11
+ * - The left subtree of a node contains only nodes with keys less than the node's key.
12
+ * - The right subtree of a node contains only nodes with keys greater than the node's key.
13
+ * - Both the left and right subtrees must also be binary search trees.
14
+ */
15
+
16
+ /**
17
+ * Definition for a binary tree node.
18
+ * function TreeNode(val, left, right) {
19
+ * this.val = (val===undefined ? 0 : val)
20
+ * this.left = (left===undefined ? null : left)
21
+ * this.right = (right===undefined ? null : right)
22
+ * }
23
+ */
24
+ /**
25
+ * @param {TreeNode } root
26
+ * @return {TreeNode }
27
+ */
28
+ var bstToGst = function ( root ) {
29
+ let sum = 0 ;
30
+ traverse ( root ) ;
31
+ return root ;
32
+
33
+ function traverse ( node ) {
34
+ if ( ! node ) return ;
35
+ traverse ( node . right ) ;
36
+ sum += node . val ;
37
+ node . val = sum ;
38
+ traverse ( node . left ) ;
39
+ }
40
+ } ;
You can’t perform that action at this time.
0 commit comments