//Tree is given in the form: (node value(left subtree)(right subtree))
//Examples:
//Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" // k = 2 //Output : 14
//Elements at level k = 2 are 6, 4, 1, 3 //sum of the digits of these elements = 6+4+1+3 = 14
//Input : tree = "(8(3(2()())(6(5()())()))(5(10()())(7(13()())())))" // k = 3 //Output : 9 //Elements at level k = 3 are 5, 1 and 3 //sum of digits of these elements = 5+1+3 = 9//logic ://1. Input 'tree' in string format and level k //2. Initialize level = -1 and sum = 0 //3. for each character 'ch' in 'tree' // 3.1 if ch == '(' then // --> level++ //3.2 else if ch == ')' then // --> level-- //3.3 else // if level == k then // sum = sum + (ch-'0') //4. Print sum
Name | Views | Likes |
---|---|---|
Sum of nodes at k-th level in a tree represented as string | 211 | 14 |
Comments