Sum of all the child nodes with even parent values in a Binary Tree
Given a binary tree, the task is to find the sum of all the nodes whose parent is even.
Examples:
Input:
1
/ \
3 8
/ \
5 6
/
1
Output: 11
The only even nodes are 8 and 6 and
the sum of their children is 5 + 6 = 11.
Input:
2
/ \
3 8
/ / \
2 5 6
/ \
1 3
Output: 25
3 + 8 + 5 + 6 + 3 = 25
Approach: Initialise sum = 0 and perform a recursive traversal of the tree and check if the node is even or not, if the node is even then add the values of its children to the sum. Finally, print the sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}
void calcSum(Node* root, int & res)
{
if (root == NULL)
return ;
if (root->data % 2 == 0) {
if (root->left)
res += root->left->data;
if (root->right)
res += root->right->data;
}
calcSum(root->left, res);
calcSum(root->right, res);
}
int findSum(Node* root)
{
int res = 0;
calcSum(root, res);
return res;
}
int main()
{
struct Node* root = newNode(2);
root->left = newNode(3);
root->right = newNode(8);
root->left->left = newNode(2);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->left = newNode(1);
root->right->right->right = newNode(3);
cout << findSum(root);
return 0;
}
|
Java
class GFG
{
static class Node
{
int data;
Node left, right;
};
static int res;
static Node newNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return (newNode);
}
static void calcSum(Node root)
{
if (root == null )
return ;
if (root.data % 2 == 0 )
{
if (root.left != null )
res += root.left.data;
if (root.right != null )
res += root.right.data;
}
calcSum(root.left);
calcSum(root.right);
}
static int findSum(Node root)
{
res = 0 ;
calcSum(root);
return res;
}
public static void main(String[] args)
{
Node root = newNode( 2 );
root.left = newNode( 3 );
root.right = newNode( 8 );
root.left.left = newNode( 2 );
root.right.left = newNode( 5 );
root.right.right = newNode( 6 );
root.right.left.left = newNode( 1 );
root.right.right.right = newNode( 3 );
System.out.print(findSum(root));
}
}
|
Python3
result = 0 ;
class Node :
def __init__( self ,data) :
self .data = data;
self .left = None
self .right = None ;
def calcSum(root, res) :
global result;
if (root = = None ) :
return ;
if (root.data % 2 = = 0 ) :
if (root.left) :
res + = root.left.data;
result = res;
if (root.right) :
res + = root.right.data;
result = res;
calcSum(root.left, res);
calcSum(root.right, res);
def findSum(root) :
res = 0 ;
calcSum(root, res);
print (result)
if __name__ = = "__main__" :
root = Node( 2 );
root.left = Node( 3 );
root.right = Node( 8 );
root.left.left = Node( 2 );
root.right.left = Node( 5 );
root.right.right = Node( 6 );
root.right.left.left = Node( 1 );
root.right.right.right = Node( 3 );
findSum(root);
|
C#
using System;
class GFG
{
class Node
{
public int data;
public Node left, right;
};
static int res;
static Node newNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return (newNode);
}
static void calcSum(Node root)
{
if (root == null )
return ;
if (root.data % 2 == 0)
{
if (root.left != null )
res += root.left.data;
if (root.right != null )
res += root.right.data;
}
calcSum(root.left);
calcSum(root.right);
}
static int findSum(Node root)
{
res = 0;
calcSum(root);
return res;
}
public static void Main(String[] args)
{
Node root = newNode(2);
root.left = newNode(3);
root.right = newNode(8);
root.left.left = newNode(2);
root.right.left = newNode(5);
root.right.right = newNode(6);
root.right.left.left = newNode(1);
root.right.right.right = newNode(3);
Console.Write(findSum(root));
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .left = null ;
this .right = null ;
}
};
var res = 0;
function newNode(data)
{
var newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return (newNode);
}
function calcSum(root)
{
if (root == null )
return ;
if (root.data % 2 == 0)
{
if (root.left != null )
res += root.left.data;
if (root.right != null )
res += root.right.data;
}
calcSum(root.left);
calcSum(root.right);
}
function findSum(root)
{
res = 0;
calcSum(root);
return res;
}
var root = newNode(2);
root.left = newNode(3);
root.right = newNode(8);
root.left.left = newNode(2);
root.right.left = newNode(5);
root.right.right = newNode(6);
root.right.left.left = newNode(1);
root.right.right.right = newNode(3);
document.write(findSum(root));
</script>
|
Time Complexity: O(n) where n is number of nodes in the given Binary Tree.
Auxiliary space: O(n) for call stack as it is using recursion
Approach 2: Iterative approach using BFS traversal
In this approach, we can perform a Breadth First Search (BFS) traversal of the binary tree using a queue data structure. For each node, we check if the parent node value is even and then add the values of its left and right child nodes if they exist. We continue the BFS traversal until we process all the nodes.
- In this approach, we use a queue to store the nodes to be processed in a BFS traversal.
- We initially push the root node onto the queue, and then for each level of the tree, we process all the nodes in that level by dequeuing them from the queue.
- For each node, we check if its parent value is even,
- and if so, we add the values of its left and right child nodes to the sum and enqueue them onto the queue.
- Otherwise, we just enqueue its child nodes onto the queue without adding their values to the sum.
- We continue the BFS traversal until we have processed all the nodes in the tree.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}
int sumEvenParent(Node* root) {
if (root == nullptr) {
return 0;
}
int sum = 0;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
for ( int i = 0; i < n; i++) {
Node* node = q.front();
q.pop();
if (node->data % 2 == 0) {
if (node->left != nullptr) {
sum += node->left->data;
q.push(node->left);
}
if (node->right != nullptr) {
sum += node->right->data;
q.push(node->right);
}
}
else {
if (node->left != nullptr) {
q.push(node->left);
}
if (node->right != nullptr) {
q.push(node->right);
}
}
}
}
return sum;
}
int main()
{
struct Node* root = newNode(2);
root->left = newNode(3);
root->right = newNode(8);
root->left->left = newNode(2);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->left = newNode(1);
root->right->right->right = newNode(3);
cout << sumEvenParent(root);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
public class SumEvenParent {
public static int sumEvenParent(Node root) {
if (root == null ) {
return 0 ;
}
int sum = 0 ;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
for ( int i = 0 ; i < n; i++) {
Node node = q.poll();
if (node.data % 2 == 0 ) {
if (node.left != null ) {
sum += node.left.data;
q.add(node.left);
}
if (node.right != null ) {
sum += node.right.data;
q.add(node.right);
}
} else {
if (node.left != null ) {
q.add(node.left);
}
if (node.right != null ) {
q.add(node.right);
}
}
}
}
return sum;
}
public static void main(String[] args) {
Node root = new Node( 2 );
root.left = new Node( 3 );
root.right = new Node( 8 );
root.left.left = new Node( 2 );
root.right.left = new Node( 5 );
root.right.right = new Node( 6 );
root.right.left.left = new Node( 1 );
root.right.right.right = new Node( 3 );
System.out.println(sumEvenParent(root));
}
}
|
Python3
from queue import Queue
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def newNode(data):
return Node(data)
def sumEvenParent(root):
if root is None :
return 0
total_sum = 0
q = Queue()
q.put(root)
while not q.empty():
n = q.qsize()
for i in range (n):
node = q.get()
if node.data % 2 = = 0 :
if node.left is not None :
total_sum + = node.left.data
q.put(node.left)
if node.right is not None :
total_sum + = node.right.data
q.put(node.right)
else :
if node.left is not None :
q.put(node.left)
if node.right is not None :
q.put(node.right)
return total_sum
if __name__ = = "__main__" :
root = newNode( 2 )
root.left = newNode( 3 )
root.right = newNode( 8 )
root.left.left = newNode( 2 )
root.right.left = newNode( 5 )
root.right.right = newNode( 6 )
root.right.left.left = newNode( 1 )
root.right.right.right = newNode( 3 )
print (sumEvenParent(root))
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree
{
static int SumEvenParent(Node root)
{
if (root == null )
{
return 0;
}
int sum = 0;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0)
{
int n = q.Count;
for ( int i = 0; i < n; i++)
{
Node node = q.Dequeue();
if (node.data % 2 == 0)
{
if (node.left != null )
{
sum += node.left.data;
q.Enqueue(node.left);
}
if (node.right != null )
{
sum += node.right.data;
q.Enqueue(node.right);
}
}
else
{
if (node.left != null )
{
q.Enqueue(node.left);
}
if (node.right != null )
{
q.Enqueue(node.right);
}
}
}
}
return sum;
}
public static void Main()
{
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(8);
root.left.left = new Node(2);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.left = new Node(1);
root.right.right.right = new Node(3);
Console.WriteLine(SumEvenParent(root));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function newNode(data) {
return new Node(data);
}
function sumEvenParent(root) {
if (root === null ) {
return 0;
}
let sum = 0;
const queue = [];
queue.push(root);
while (queue.length > 0) {
const n = queue.length;
for (let i = 0; i < n; i++) {
const node = queue.shift();
if (node.data % 2 === 0) {
if (node.left !== null ) {
sum += node.left.data;
queue.push(node.left);
}
if (node.right !== null ) {
sum += node.right.data;
queue.push(node.right);
}
} else {
if (node.left !== null ) {
queue.push(node.left);
}
if (node.right !== null ) {
queue.push(node.right);
}
}
}
}
return sum;
}
const root = newNode(2);
root.left = newNode(3);
root.right = newNode(8);
root.left.left = newNode(2);
root.right.left = newNode(5);
root.right.right = newNode(6);
root.right.left.left = newNode(1);
root.right.right.right = newNode(3);
console.log(sumEvenParent(root));
|
The time complexity of this approach is O(n), where n is the number of nodes in the binary tree, since we need to visit each node once in the worst case.
The space complexity of this approach is O(w), where w is the maximum width of the binary tree, since at any point in time, the queue will hold at most w nodes.
In the worst case, the width of the binary tree is n/2, so the space complexity is O(n).
Last Updated :
10 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...