Given a binary tree and a number K, the task is to find sum of tree nodes at level k. The Binary Tree s given in string form: (node-value(left-subtree)(right-subtree)).
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer K denoting level of Binary Tree for which we need sum. Next line is string which represents Binary Tree.
Output:
Print the Sum of all the elements at k level in each line.
Constraints:
1<=T<=100
1<=K<=20
Example:
Input:
1
2
(0(5(6()())(4()(9()())))(7(1()())(3()())))
Output:
14
Explaination:
The Tree from the above String will formed as:
0
/ \
5 7
/ \ / \
6 4 1 3
\
9
最开始被输入方式迷了,其实括号就可以帮我们判断处于第几层!!!
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
cin >> T;
while(T--) {
int k;
cin >> k;
string str;
cin >> str;
int ans = 0;
int lev = 0;
for(int i = 0; str[i]; ++i) {
if(str[i] == '(') {
lev++;
} else if(str[i] == ')') {
lev--;
} else if(lev == k+1) {
int j = i+1;
while(str[j] != '(' && str[j] != ')') j++;
int tmp = 0, p = 1;
for(int k = j-1; k >= i; --k) {
tmp += (str[k] - '0') * p;
p *= 10;
}
ans += tmp;
i = j-1;
}
}
cout << ans << endl;
}
return 0;
}