Binary Tree K level sum (samsung)
来源:互联网 发布:影音后期制作软件大全 编辑:程序博客网 时间:2024/06/01 12:53
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;}
- Binary Tree K level sum (samsung)
- leetCode: binary tree sum
- Binary Tree Path Sum
- Binary Tree Path Sum
- Binary Tree Path Sum
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Linux--RH254---unit 8 mariadb数据库
- MATLAB面向对象编程命名空间的使用
- 二叉树遍历
- ASP.NET HttpModule的使用说明
- C和指针 练习 1-3
- Binary Tree K level sum (samsung)
- 在“一带一路”上,有哪些国家?
- 非虚方法的调用
- 无数个骂娘的故事告诉你,千万别做技术合伙人!
- python基础知识(3)
- Linux--RH254---unit 2 高级网络配置
- 给定N张扑克牌和一个随机函数,设计一个洗牌算法
- 二叉树常见的面试题(1)
- Linux--RH254---unit 9 apache web服务