Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.
Input:
First line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below:
The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child.
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
Output:
For each test case prints the maximum sum such that no two nodes are adjacent.
Constraints:
1 <= T <= 100
1 <= N <= 1000
Your Task:
This is a functional problem. User need to complete function getMaxSum() which accepts root node of the tree as parameter and returns the maximum sum .
Example:
Input:
2
11 1 2
1 2 3 4 N 5 6
Output:
11
16
Explanation:
Testcase 1: The maximum sum is sum of node 11.
Testcase 2: The maximum sum is sum of nodes 1 4 5 6 , i.e 16. These nodes are non adjacent.
If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.
Sulagna | 117 |
RUTVIKHARIPARA | 116 |
janvidavda105190 | 93 |
harshsiddhapura105461 | 93 |
devsinghindra | 80 |
PiyushPandey4 | 614 |
ASWATHAMA | 561 |
akhyasharma01 | 547 |
john_wick | 521 |
jagrit_07 | 443 |
blackshadows | 5362 |
Ibrahim Nash | 5242 |
akhayrutdinov | 5111 |
mb1973 | 4929 |
Quandray | 4598 |