forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertBSTtoGreaterTree.java
65 lines (55 loc) · 2.08 KB
/
ConvertBSTtoGreaterTree.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
/**
* 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.
Example:
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13
*/
public class ConvertBSTtoGreaterTree {
//This solution is generic for both BST and regular binary trees
public TreeNode convertBST(TreeNode root) {
if (root == null) return root;
List<Integer> list = new ArrayList<>();
putNodeToList(list, root);
Collections.sort(list);
int[] sums = new int[list.size()];
sums[list.size()-1] = 0;
for (int i = list.size()-2; i >= 0; i--) {
sums[i] = sums[i+1] + list.get(i+1);
}
TreeMap<Integer, Integer> treeMap = new TreeMap<>();
for (int i = 0; i < list.size(); i++) {
treeMap.put(list.get(i), sums[i]);
}
TreeNode result = new TreeNode(treeMap.get(list.get(0)));
return generateResultRoot(root, treeMap, result);
}
private TreeNode generateResultRoot(TreeNode root, TreeMap<Integer, Integer> treeMap, TreeNode result) {
if (root != null) result.val = treeMap.get(root.val) + root.val;
if (root.left != null) {
result.left = new TreeNode(0);
generateResultRoot(root.left, treeMap, result.left);
}
if (root.right != null) {
result.right = new TreeNode(0);
generateResultRoot(root.right, treeMap, result.right);
}
return result;
}
private void putNodeToList(List<Integer> list, TreeNode root) {
if (root != null) list.add(root.val);
if (root.left != null) putNodeToList(list, root.left);
if (root.right != null) putNodeToList(list, root.right);
}
}