Given a binary tree of integers and a depth, the goal is to find the sum of all node values at the depth in the tree. The root is considered depth 0, and the tree is given as a string in the format: (<node-value>(<left subtree>)(<right subtree>)). For example, treeLevelSum("(5(42)(-37(28)()))", 1) should return 5.
int treeLevelSum(String tree, int k) {
int sum = 0;
int depth = 0;
int value = 0;
int sign = 1;
for (int i = 1; i < tree.length(); i++) {
if (tree.charAt(i) == '(') {
depth += 1;
} else if (tree.charAt(i) == ')') {
sum += value * sign;
value = 0;
sign = 1;
depth -= 1;
} else if (depth == k) {
if (tree.charAt(i) == '-') {
sign = -1;
} else {
value = value * 10 + (tree.charAt(i) - '0');
}
}
}
return sum;
}
I was just wondering if there was a better way of parsing this, or if there was any way of improving efficiency? Is there a known "best solution" for this kind of problem?