# Sum of specially balanced nodes from a given Binary Tree

Given a Binary Tree, the task is to find the sum of all the specially balanced nodes in the given Binary Tree.

A specially balanced node in a Binary Tree contains the sum of nodes of one subtree(either left or right) as even and the sum of the other subtree as odd.
The nodes having only one child or no child can never be a balanced node.

Examples:

Input: Below is the given Tree: Output: 33
Explanation:
The specially balanced nodes are 11 and 22.
For Node 11:
The sum of left subtree is (23 + 13 + 9) = 45 which is Odd.
The sum of right subtree is (44 + 22 + 7 + 6 + 15) = 94 which is Even.
For Node 22:
The sum of left subtree is 6 which is Even.
The sum of right subtree is 15 which is Odd.
Therefore, the sum of specially balanced nodes is 11 + 22 = 33.

Input: Below is the given Tree: Output: 16
Explanation:
The specially balanced nodes are 4 and 12.
For Node 4:
The sum of left subtree is 2 which is Even.
The sum of right subtree is 3 which is Odd.
For Node 12:
The sum of left subtree is 17 which is Odd.
The sum of right subtree is (16 + 4 + 9 + 2 + 3) = 34 which is Even.
Therefore, the sum of specially balanced nodes is 4 + 12 = 16.

Approach: The idea is to perform DFS Traversal on the given Tree using recursion and update the final sum as per the given conditions. Follow the steps below:

1. Initialize a totalSum as 0 which stores the sum of all specially balanced nodes.
2. Perform the DFS Traversal on the given Tree and check for the following:
• If the node is a leaf node, then return the value of that node.
• Now, if the current node is not a leaf node, recursively traverse for the left and right subtree.
• Return the value of the sum of the left and right subtree with the current root value when each recursive call ends.
• Check if the returned sums satisfy the property of the specially balanced node. IF found to be true, add the current node value to totalSum.
3. Print the value of totalSum after completing the above steps.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Structure of Binary Tree` `struct` `Node {` `    ``int` `data;` `    ``Node *left, *right;` `};`   `// Function to create a new node` `Node* newnode(``int` `data)` `{` `    ``Node* temp = ``new` `Node;` `    ``temp->data = data;` `    ``temp->left = NULL;` `    ``temp->right = NULL;`   `    ``// Return the created node` `    ``return` `temp;` `}`   `// Function to insert a node in the tree` `Node* insert(string s, ``int` `i, ``int` `N,` `             ``Node* root, Node* temp)` `{` `    ``if` `(i == N)` `        ``return` `temp;`   `    ``// Left insertion` `    ``if` `(s[i] == ``'L'``)` `        ``root->left = insert(s, i + 1, N,` `                            ``root->left,` `                            ``temp);`   `    ``// Right insertion` `    ``else` `        ``root->right = insert(s, i + 1, N,` `                             ``root->right,` `                             ``temp);`   `    ``// Return the root node` `    ``return` `root;` `}`   `// Function to find sum of specially` `// balanced nodes in the Tree` `int` `SBTUtil(Node* root, ``int``& sum)` `{` `    ``// Base Case` `    ``if` `(root == NULL)` `        ``return` `0;`   `    ``if` `(root->left == NULL` `        ``&& root->right == NULL)` `        ``return` `root->data;`   `    ``// Find the left subtree sum` `    ``int` `left = SBTUtil(root->left, sum);`   `    ``// Find the right subtree sum` `    ``int` `right = SBTUtil(root->right, sum);`   `    ``// Condition of specially` `    ``// balanced node` `    ``if` `(root->left && root->right) {`   `        ``// Condition of specially` `        ``// balanced node` `        ``if` `((left % 2 == 0` `             ``&& right % 2 != 0)` `            ``|| (left % 2 != 0` `                ``&& right % 2 == 0)) {`   `            ``sum += root->data;` `        ``}` `    ``}`   `    ``// Return the sum` `    ``return` `left + right + root->data;` `}`   `// Function to build the binary tree` `Node* build_tree(``int` `R, ``int` `N,` `                 ``string str[],` `                 ``int` `values[])` `{` `    ``// Form root node of the tree` `    ``Node* root = newnode(R);` `    ``int` `i;`   `    ``// Insert nodes into tree` `    ``for` `(i = 0; i < N - 1; i++) {` `        ``string s = str[i];` `        ``int` `x = values[i];`   `        ``// Create a new Node` `        ``Node* temp = newnode(x);`   `        ``// Insert the node` `        ``root = insert(s, 0, s.size(),` `                      ``root, temp);` `    ``}`   `    ``// Return the root of the Tree` `    ``return` `root;` `}`   `// Function to find the sum of specially` `// balanced nodes` `void` `speciallyBalancedNodes(` `    ``int` `R, ``int` `N, string str[], ``int` `values[])` `{` `    ``// Build Tree` `    ``Node* root = build_tree(R, N,` `                            ``str, values);`   `    ``// Stores the sum of specially` `    ``// balanced node` `    ``int` `sum = 0;`   `    ``// Function Call` `    ``SBTUtil(root, sum);`   `    ``// Print required sum` `    ``cout << sum << ``" "``;` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given nodes` `    ``int` `N = 7;`   `    ``// Given root` `    ``int` `R = 12;`   `    ``// Given path info of nodes` `    ``// from root` `    ``string str[N - 1]` `        ``= { ``"L"``, ``"R"``, ``"RL"``,` `            ``"RR"``, ``"RLL"``, ``"RLR"` `};`   `    ``// Given node values` `    ``int` `values[N - 1] = { 17, 16, 4,` `                          ``9, 2, 3 };`   `    ``// Function Call` `    ``speciallyBalancedNodes(R, N, str,` `                           ``values);`   `    ``return` `0;` `}`

## Java

 `// Java program for ` `// the above approach` `import` `java.util.*;` `class` `GFG{` `  `  `static` `int` `sum;`   `//Structure of Binary Tree` `static` `class` `Node ` `{` `  ``int` `data;` `  ``Node left, right;` `};`   `//Function to create a new node` `static` `Node newnode(``int` `data)` `{` `  ``Node temp = ``new` `Node();` `  ``temp.data = data;` `  ``temp.left = ``null``;` `  ``temp.right = ``null``;`   `  ``// Return the created node` `  ``return` `temp;` `}`   `//Function to insert a node in the tree` `static` `Node insert(String s, ``int` `i, ``int` `N,` `                   ``Node root, Node temp)` `{` `  ``if` `(i == N)` `    ``return` `temp;`   `  ``// Left insertion` `  ``if` `(s.charAt(i) == ``'L'``)` `    ``root.left = insert(s, i + ``1``, N,` `                       ``root.left, temp);`   `  ``// Right insertion` `  ``else` `    ``root.right = insert(s, i + ``1``, N,` `                        ``root.right, temp);` `  `  `  ``// Return the root node` `  ``return` `root;` `}`   `//Function to find sum of specially` `//balanced nodes in the Tree` `static` `int` `SBTUtil(Node root)` `{` `  ``// Base Case` `  ``if` `(root == ``null``)` `    ``return` `0``;`   `  ``if` `(root.left == ``null` `&& ` `      ``root.right == ``null``)` `    ``return` `root.data;`   `  ``// Find the left subtree sum` `  ``int` `left = SBTUtil(root.left);`   `  ``// Find the right subtree sum` `  ``int` `right = SBTUtil(root.right);`   `  ``// Condition of specially` `  ``// balanced node` `  ``if` `(root.left != ``null` `&& ` `      ``root.right != ``null``) ` `  ``{` `    ``// Condition of specially` `    ``// balanced node` `    ``if` `((left % ``2` `== ``0` `&& right % ``2` `!= ``0``) || ` `        ``(left % ``2` `!= ``0` `&& right % ``2` `== ``0``)) ` `    ``{` `      ``sum += root.data;` `    ``}` `  ``}`   `  ``// Return the sum` `  ``return` `left + right + root.data;` `}`   `//Function to build the binary tree` `static` `Node build_tree(``int` `R, ``int` `N,` `                       ``String str[],` `                       ``int` `values[])` `{` `  ``// Form root node of the tree` `  ``Node root = newnode(R);` `  ``int` `i;`   `  ``// Insert nodes into tree` `  ``for` `(i = ``0``; i < N - ``1``; i++) ` `  ``{` `    ``String s = str[i];` `    ``int` `x = values[i];`   `    ``// Create a new Node` `    ``Node temp = newnode(x);`   `    ``// Insert the node` `    ``root = insert(s, ``0``, s.length(),` `                  ``root, temp);` `  ``}`   `  ``// Return the root of the Tree` `  ``return` `root;` `}`   `// Function to find the ` `// sum of specially` `// balanced nodes` `static` `void` `speciallyBalancedNodes(``int` `R, ``int` `N, ` `                                   ``String str[], ` `                                   ``int` `values[])` `{` `  ``// Build Tree` `  ``Node root = build_tree(R, N, str, ` `                         ``values);`   `  ``// Stores the sum of specially` `  ``// balanced node` `  ``sum = ``0``;`   `  ``// Function Call` `  ``SBTUtil(root);`   `  ``// Print required sum` `  ``System.out.print(sum + ``" "``);` `}`   `//Driver Code` `public` `static` `void` `main(String[] args)` `{` `  ``// Given nodes` `  ``int` `N = ``7``;`   `  ``// Given root` `  ``int` `R = ``12``;`   `  ``// Given path info of nodes` `  ``// from root` `  ``String str[] = {``"L"``, ``"R"``, ``"RL"``,` `                 ``"RR"``, ``"RLL"``, ``"RLR"``};`   `  ``// Given node values` `  ``int` `values[] = {``17``, ``16``, ``4``,` `                  ``9``, ``2``, ``3``};`   `  ``// Function Call` `  ``speciallyBalancedNodes(R, N, str,` `                         ``values);` `}` `}`   `//This code is contributed by 29AjayKumar`

## Python3

 `# Python3 program for the above approach`   `# Structure of Binary Tree` `class` `Node:`   `    ``def` `__init__(``self``, data):` `        `  `        ``self``.data ``=` `data` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `# Function to create a new node` `def` `newnode(data):`   `    ``temp ``=` `Node(data)` `    `  `    ``# Return the created node` `    ``return` `temp`   `# Function to insert a node in the tree` `def` `insert(s, i, N, root, temp):` `    `  `    ``if` `(i ``=``=` `N):` `        ``return` `temp`   `    ``# Left insertion` `    ``if` `(s[i] ``=``=` `'L'``):` `        ``root.left ``=` `insert(s, i ``+` `1``, N,` `                           ``root.left, temp)`   `    ``# Right insertion` `    ``else``:` `        ``root.right ``=` `insert(s, i ``+` `1``, N, ` `                            ``root.right, temp)`   `    ``# Return the root node` `    ``return` `root`   `# Function to find sum of specially` `# balanced nodes in the Tree` `def` `SBTUtil(root, ``sum``):` `    `  `    ``# Base Case` `    ``if` `(root ``=``=` `None``):` `        ``return` `[``0``, ``sum``]`   `    ``if` `(root.left ``=``=` `None` `and` `       ``root.right ``=``=` `None``):` `        ``return` `[root.data, ``sum``]`   `    ``# Find the left subtree sum` `    ``left, ``sum` `=` `SBTUtil(root.left, ``sum``)`   `    ``# Find the right subtree sum` `    ``right, ``sum` `=` `SBTUtil(root.right, ``sum``)`   `    ``# Condition of specially` `    ``# balanced node` `    ``if` `(root.left ``and` `root.right):` `        `  `        ``# Condition of specially` `        ``# balanced node` `        ``if` `((left ``%` `2` `=``=` `0` `and` `            ``right ``%` `2` `!``=` `0``) ``or` `            ``(left ``%` `2` `!``=` `0` `and` `            ``right ``%` `2` `=``=` `0``)):` `            ``sum` `+``=` `root.data`   `    ``# Return the sum` `    ``return` `[left ``+` `right ``+` `root.data, ``sum``]`   `# Function to build the binary tree` `def` `build_tree(R, N, ``str``, values):` `    `  `    ``# Form root node of the tree` `    ``root ``=` `newnode(R)`   `    ``# Insert nodes into tree` `    ``for` `i ``in` `range``(``0``, N ``-` `1``):` `        ``s ``=` `str``[i]` `        ``x ``=` `values[i]`   `        ``# Create a new Node` `        ``temp ``=` `newnode(x)`   `        ``# Insert the node` `        ``root ``=` `insert(s, ``0``, ``len``(s), ` `                      ``root, temp)` `    `  `    ``# Return the root of the Tree` `    ``return` `root`   `# Function to find the sum of specially` `# balanced nodes` `def` `speciallyBalancedNodes(R, N, ``str``, values):`   `    ``# Build Tree` `    ``root ``=` `build_tree(R, N, ``str``, values)`   `    ``# Stores the sum of specially` `    ``# balanced node` `    ``sum` `=` `0`   `    ``# Function Call` `    ``tmp, ``sum` `=` `SBTUtil(root, ``sum``)`   `    ``# Print required sum` `    ``print``(``sum``, end ``=` `' '``)`   `# Driver code` `if` `__name__ ``=``=` `"__main__"``:` `    `  `    ``# Given nodes` `    ``N ``=` `7`   `    ``# Given root` `    ``R ``=` `12`   `    ``# Given path info of nodes` `    ``# from root` `    ``str` `=` `[ ``"L"``, ``"R"``, ``"RL"``, ` `            ``"RR"``, ``"RLL"``, ``"RLR"` `]`   `    ``# Given node values` `    ``values ``=` `[ ``17``, ``16``, ``4``, ``9``, ``2``, ``3` `]`   `    ``# Function Call` `    ``speciallyBalancedNodes(R, N, ``str``,` `                           ``values)`   `# This code is contributed by rutvik_56`

## C#

 `//C# program for ` `// the above approach` `using` `System;` `class` `GFG{` `  `  `static` `int` `sum;`   `//Structure of Binary Tree` `class` `Node ` `{` `  ``public` `int` `data;` `  ``public` `Node left, right;` `};`   `//Function to create a new node` `static` `Node newnode(``int` `data)` `{` `  ``Node temp = ``new` `Node();` `  ``temp.data = data;` `  ``temp.left = ``null``;` `  ``temp.right = ``null``;`   `  ``// Return the created node` `  ``return` `temp;` `}`   `//Function to insert a node in the tree` `static` `Node insert(String s, ``int` `i, ``int` `N,` `                   ``Node root, Node temp)` `{` `  ``if` `(i == N)` `    ``return` `temp;`   `  ``// Left insertion` `  ``if` `(s[i] == ``'L'``)` `    ``root.left = insert(s, i + 1, N,` `                       ``root.left, temp);`   `  ``// Right insertion` `  ``else` `    ``root.right = insert(s, i + 1, N,` `                        ``root.right, temp);` `  `  `  ``// Return the root node` `  ``return` `root;` `}`   `//Function to find sum of specially` `//balanced nodes in the Tree` `static` `int` `SBTUtil(Node root)` `{` `  ``// Base Case` `  ``if` `(root == ``null``)` `    ``return` `0;`   `  ``if` `(root.left == ``null` `&& ` `      ``root.right == ``null``)` `    ``return` `root.data;`   `  ``// Find the left subtree sum` `  ``int` `left = SBTUtil(root.left);`   `  ``// Find the right subtree sum` `  ``int` `right = SBTUtil(root.right);`   `  ``// Condition of specially` `  ``// balanced node` `  ``if` `(root.left != ``null` `&& ` `      ``root.right != ``null``) ` `  ``{` `    ``// Condition of specially` `    ``// balanced node` `    ``if` `((left % 2 == 0 && right % 2 != 0) || ` `        ``(left % 2 != 0 && right % 2 == 0)) ` `    ``{` `      ``sum += root.data;` `    ``}` `  ``}`   `  ``// Return the sum` `  ``return` `left + right + root.data;` `}`   `//Function to build the binary tree` `static` `Node build_tree(``int` `R, ``int` `N,` `                       ``String []str,` `                       ``int` `[]values)` `{` `  ``// Form root node of the tree` `  ``Node root = newnode(R);` `  ``int` `i;`   `  ``// Insert nodes into tree` `  ``for` `(i = 0; i < N - 1; i++) ` `  ``{` `    ``String s = str[i];` `    ``int` `x = values[i];`   `    ``// Create a new Node` `    ``Node temp = newnode(x);`   `    ``// Insert the node` `    ``root = insert(s, 0, s.Length,` `                  ``root, temp);` `  ``}`   `  ``// Return the root of the Tree` `  ``return` `root;` `}`   `// Function to find the ` `// sum of specially` `// balanced nodes` `static` `void` `speciallyBalancedNodes(``int` `R, ``int` `N, ` `                                   ``String []str, ` `                                   ``int` `[]values)` `{` `  ``// Build Tree` `  ``Node root = build_tree(R, N, str, ` `                         ``values);`   `  ``// Stores the sum of specially` `  ``// balanced node` `  ``sum = 0;`   `  ``// Function Call` `  ``SBTUtil(root);`   `  ``// Print required sum` `  ``Console.Write(sum + ``" "``);` `}`   `//Driver Code` `public` `static` `void` `Main(String[] args)` `{` `  ``// Given nodes` `  ``int` `N = 7;`   `  ``// Given root` `  ``int` `R = 12;`   `  ``// Given path info of nodes` `  ``// from root` `  ``String []str = {``"L"``, ``"R"``, ``"RL"``,` `                  ``"RR"``, ``"RLL"``, ``"RLR"``};`   `  ``// Given node values` `  ``int` `[]values = {17, 16, 4,` `                  ``9, 2, 3};`   `  ``// Function Call` `  ``speciallyBalancedNodes(R, N, str,` `                         ``values);` `}` `}`   `// This code is contributed by 29AjayKumar`

Output:

```16

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : 29AjayKumar, rutvik_56

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.