Binary Tree K level sum (samsung)

本文介绍了一种算法,该算法接收一个二叉树及其字符串形式表示与一个整数K作为输入,输出二叉树第K层节点值的总和。通过遍历字符串并跟踪层级来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

(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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值