Problem : A binary tree is given as an input, each node of binary tree contains one integer value. Find the maximum sum of collection of nodes such that following two conditions are met.
- if node's parent node is considered for sum, then node cannot be considered.
- if node's either of child is considered for sum, then node cannot be considered.
For example :
For a binary tree
15
20 25
5 15 5
The max sum we can get is considering [20, 25]
which is 45
.
To implement this I used O(n^2) approach and code is here.
I am trying to optimize it and looking for feedback on improving algorithm, code efficiency and cleanliness
tree
is String representation of tree, given in BFS manner. _
is present in place of null element. _
is not given for the deepest level's element's null representation.
the above tree would be represented as 15 20 25 5 15 5 _
static int findMaxSum(String tree) {
String[] tokens = tree.split(" ");
int max = 0;
for (int i = 0; i < tokens.length; i++) {
if (!isValidToken(tokens[i])) {
continue;
}
Set<Integer> set = new HashSet<>();
//wildcard entry
set.add(i);
int sum = Integer.parseInt(tokens[i]);
for (int j = 0; j < tokens.length; j++) {
if (isValidToken(tokens[j])) {
if(!set.contains(j) && !set.contains(getParentIndex(j))){
if (!set.contains(getLeftChildIndex(j)) && !set.contains(getRightChildIndex(j))) {
set.add(j);
sum += Integer.parseInt(tokens[j]);
}
}
}
}
max = Math.max(max,sum);
}
return max;
}
static boolean isValidToken(String token) {
return !"_".equals(token);
}
static int getLeftChildIndex(int parentIndex) {
return parentIndex * 2 + 1;
}
static int getRightChildIndex(int parentIndex) {
return parentIndex * 2 + 2;
}
static int getParentIndex(int childIndex) {
return (childIndex - 1)/2;
}
Note: this code works but it is not efficient. I am looking for ideas on how to improve it.