-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvertBSTToGreaterTree.java
More file actions
36 lines (24 loc) · 927 Bytes
/
Copy pathConvertBSTToGreaterTree.java
File metadata and controls
36 lines (24 loc) · 927 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Given a Binary Search Tree (BST), convert it to a Greater Tree
// such that every key of the original BST is changed to the original key
// plus sum of all keys greater than the original key in BST.
// See: https://leetcode.com/problems/convert-bst-to-greater-tree/
package leetcode.tree;
import static leetcode.util.tree.BinTreeUtil.initTree;
import static leetcode.util.tree.BinTreeUtil.printInorder;
import leetcode.util.tree.TreeNode;
public class ConvertBSTToGreaterTree {
private int prev = 0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
convertBST(root.right);
root.val += prev;
prev = root.val;
convertBST(root.left);
}
return root;
}
public static void main(String[] args) {
TreeNode t1 = initTree(5, 2, 13);
printInorder(new ConvertBSTToGreaterTree().convertBST(t1));
}
}