Skip to content

Commit ce55ae4

Browse files
committed
Add solution #538
1 parent 63c6946 commit ce55ae4

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,7 @@
428428
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
429429
532|[K-diff Pairs in an Array](./0532-k-diff-pairs-in-an-array.js)|Medium|
430430
537|[Complex Number Multiplication](./0537-complex-number-multiplication.js)|Medium|
431+
538|[Convert BST to Greater Tree](./0538-convert-bst-to-greater-tree.js)|Medium|
431432
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
432433
542|[01 Matrix](./0542-01-matrix.js)|Medium|
433434
543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 538. Convert BST to Greater Tree
3+
* https://leetcode.com/problems/convert-bst-to-greater-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 convertBST = 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+
};

0 commit comments

Comments
 (0)