Sum of all the child nodes with even parent values in a Binary Tree
Last Updated :
10 Feb, 2024
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++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// A binary tree node
struct Node {
int data;
struct Node *left, *right;
};
// A utility function to allocate a new node
struct Node* newNode(int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}
// This function visit each node in preorder fashion
// And adds the values of the children of a node with
// even value to the res variable
void calcSum(Node* root, int& res)
{
// Base Case
if (root == NULL)
return;
// If the value of the
// current node if even
if (root->data % 2 == 0) {
// If the left child of the even
// node exist then add it to the res
if (root->left)
res += root->left->data;
// Do the same with the right child
if (root->right)
res += root->right->data;
}
// Visiting the left subtree and the right
// subtree just like preorder traversal
calcSum(root->left, res);
calcSum(root->right, res);
}
// Function to return the sum of nodes
// whose parent has even value
int findSum(Node* root)
{
// Initialize result
int res = 0;
calcSum(root, res);
return res;
}
// Driver code
int main()
{
// Creating the tree
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);
// Print the required sum
cout << findSum(root);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// A binary tree node
static class Node
{
int data;
Node left, right;
};
static int res;
// A utility function to allocate a new node
static Node newNode(int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null;
return (newNode);
}
// This function visit each node in preorder fashion
// And adds the values of the children of a node with
// even value to the res variable
static void calcSum(Node root)
{
// Base Case
if (root == null)
return;
// If the value of the
// current node if even
if (root.data % 2 == 0)
{
// If the left child of the even
// node exist then add it to the res
if (root.left != null)
res += root.left.data;
// Do the same with the right child
if (root.right != null)
res += root.right.data;
}
// Visiting the left subtree and the right
// subtree just like preorder traversal
calcSum(root.left);
calcSum(root.right);
}
// Function to return the sum of nodes
// whose parent has even value
static int findSum(Node root)
{
// Initialize result
res = 0;
calcSum(root);
return res;
}
// Driver code
public static void main(String[] args)
{
// Creating the tree
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);
// Print the required sum
System.out.print(findSum(root));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 implementation of the approach
result = 0;
# A binary tree node
class Node :
def __init__(self,data) :
self.data = data;
self.left = None
self.right = None;
# This function visit each node in preorder fashion
# And adds the values of the children of a node with
# even value to the res variable
def calcSum(root, res) :
global result;
# Base Case
if (root == None) :
return;
# If the value of the
# current node if even
if (root.data % 2 == 0) :
# If the left child of the even
# node exist then add it to the res
if (root.left) :
res += root.left.data;
result = res;
# Do the same with the right child
if (root.right) :
res += root.right.data;
result = res;
# Visiting the left subtree and the right
# subtree just like preorder traversal
calcSum(root.left, res);
calcSum(root.right, res);
# Function to return the sum of nodes
# whose parent has even value
def findSum(root) :
res = 0;
calcSum(root, res);
print(result)
# Driver code
if __name__ == "__main__" :
# Creating the tree
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);
# Print the required sum
findSum(root);
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// A binary tree node
class Node
{
public int data;
public Node left, right;
};
static int res;
// A utility function to allocate a new node
static Node newNode(int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null;
return (newNode);
}
// This function visit each node in preorder fashion
// And adds the values of the children of a node with
// even value to the res variable
static void calcSum(Node root)
{
// Base Case
if (root == null)
return;
// If the value of the
// current node if even
if (root.data % 2 == 0)
{
// If the left child of the even
// node exist then add it to the res
if (root.left != null)
res += root.left.data;
// Do the same with the right child
if (root.right != null)
res += root.right.data;
}
// Visiting the left subtree and the right
// subtree just like preorder traversal
calcSum(root.left);
calcSum(root.right);
}
// Function to return the sum of nodes
// whose parent has even value
static int findSum(Node root)
{
// Initialize result
res = 0;
calcSum(root);
return res;
}
// Driver code
public static void Main(String[] args)
{
// Creating the tree
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);
// Print the required sum
Console.Write(findSum(root));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation of the approach
// A binary tree node
class Node
{
constructor()
{
this.data = 0;
this.left = null;
this.right = null;
}
};
var res = 0;
// A utility function to allocate a new node
function newNode(data)
{
var newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null;
return (newNode);
}
// This function visit each node in preorder fashion
// And adds the values of the children of a node with
// even value to the res variable
function calcSum(root)
{
// Base Case
if (root == null)
return;
// If the value of the
// current node if even
if (root.data % 2 == 0)
{
// If the left child of the even
// node exist then add it to the res
if (root.left != null)
res += root.left.data;
// Do the same with the right child
if (root.right != null)
res += root.right.data;
}
// Visiting the left subtree and the right
// subtree just like preorder traversal
calcSum(root.left);
calcSum(root.right);
}
// Function to return the sum of nodes
// whose parent has even value
function findSum(root)
{
// Initialize result
res = 0;
calcSum(root);
return res;
}
// Driver code
// Creating the tree
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);
// Print the required sum
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++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// A binary tree node
struct Node {
int data;
struct Node *left, *right;
};
// A utility function to allocate a new node
struct Node* newNode(int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}
// This function visit each node in preorder fashion
// And adds the values of the children of a node with
// even value to the res variable
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;
}
// Driver code
int main()
{
// Creating the tree
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);
// Print the required sum
cout << sumEvenParent(root);
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
// A binary tree node
class Node {
int data;
Node left, right;
// Constructor to create a new node
Node(int item) {
data = item;
left = right = null;
}
}
public class SumEvenParent {
// This function visit each node in preorder fashion
// And adds the values of the children of a node with
// even value to the res variable
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;
}
// Driver code
public static void main(String[] args) {
// Creating the tree
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);
// Print the required sum
System.out.println(sumEvenParent(root));
}
}
// This code is contributed by Yash Agarwal(yashagarwal2852002)
Python3
from queue import Queue
# A binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# A utility function to allocate a new node
def newNode(data):
return Node(data)
# This function visits each node in a preorder fashion
# and adds the values of the children of a node with
# an even value to the result variable
def sumEvenParent(root):
if root is None:
return 0
# Initialize sum to store the result
total_sum = 0
# Use a queue for level order traversal
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 the node has an even value, add the values of its children to the sum
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 the node has an odd value, simply enqueue its children for further traversal
if node.left is not None:
q.put(node.left)
if node.right is not None:
q.put(node.right)
return total_sum
# Driver code
if __name__ == "__main__":
# Creating the tree
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 the required sum
print(sumEvenParent(root))
C#
using System;
using System.Collections.Generic;
// A binary tree node
class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
// This function visits each node in preorder fashion
// and adds the values of the children of a node with
// even value to the sum variable
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;
}
// Driver code
public static void Main()
{
// Creating the tree
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);
// Print the required sum
Console.WriteLine(SumEvenParent(root));
}
}
JavaScript
// JavaScript implementation of the approach
// A binary tree node
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// A utility function to allocate a new node
function newNode(data) {
return new Node(data);
}
// This function visits each node in level-order fashion
// And adds the values of the children of a node with
// even value to the sum variable
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;
}
// Driver code to test the function
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);
// Print the required sum
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).
Similar Reads
Sum of all the child nodes with even grandparents in a Binary Tree
Given a Binary Tree, calculate the sum of nodes with even valued Grandparents.Examples: Input: 22 / \ 3 8 / \ / \ 4 8 1 9 \ 2 Output: 24 Explanation The nodes 4, 8, 2, 1, 9 has even value grandparents. Hence sum = 4 + 8 + 1 + 9 + 2 = 24. Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / 8 Output: 8 Explanation Onl
6 min read
Sum of nodes in a Binary Search Tree with values from a given range
Given a Binary Search Tree consisting of n nodes and two positive integers l and r, the task is to find the sum of values of all the nodes that lie in the range [l, r].Examples:Input: Output: 32Explanation: The nodes in the given Tree that lies in the range [7, 15] are {7, 10, 15}. Therefore, the su
6 min read
Find sum of all nodes of the given perfect binary tree
Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a progr
11 min read
Find parent of given node in a Binary Tree with given postorder traversal
Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first 2^{N}-1 natural numbers (1, 2, ... 2^{N}-1) For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2 4 5 Examples: Input: N =
9 min read
Sum of nodes in the right view of the given binary tree
Given a binary tree, the task is to find the sum of the nodes which are visible in the right view. The right view of a binary tree is the set of nodes visible when the tree is viewed from the right.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6Output: 101 + 3 + 6 = 10Input: 1 / \ 2 3 \ 4 \ 5 \ 6Output: 19Ap
15+ min read
Replace each node of a Binary Tree with the sum of all the nodes present in its diagonal
Given a Binary Tree, the task is to print the level order traversal of the tree after replacing the value of each node of the tree with the sum of all the nodes on the same diagonal. Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: 30 21 30 9 21 30 3 9 21 Explanation: 30 / \ 21 30 / \ \
11 min read
Number of pairs with a given sum in a Binary Search Tree
Given a Binary Search Tree, and a number X. The task is to find the number of distinct pairs of distinct nodes in BST with a sum equal to X. No two nodes have the same values. Examples: Input : X = 5 5 / \ 3 7 / \ / \ 2 4 6 8 Output : 1 {2, 3} is the only possible pair. Thus, the answer is equal to
9 min read
Queries to find the sum of weights of all nodes with vertical width from given range in a Binary Tree
Given a Binary Tree consisting of N nodes having values in the range [0, N - 1] rooted as 0, an array wt[] of size N where wt[i] is the weight of the ith node and a 2D array Q[][] consisting of queries of the type {L, R}, the task for each query is to find the sum of weights of all nodes whose verti
11 min read
Remove all subtrees consisting only of even valued nodes from a Binary Tree
Given a Binary Tree, the task is to remove all the subtrees that do not contain any odd valued node. Print the Levelorder Traversal of the tree after removal of these subtrees. Note: Print NULL for removed nodes. Examples: Input: Below is the given Tree: 1 \ 2 / \ 8 5Output: 1 NULL 2 NULL 5Explanati
8 min read
Count pairs in a binary tree whose sum is equal to a given value x
Given a binary tree containing n distinct numbers and a value x. The problem is to count pairs in the given binary tree whose sum is equal to the given value x. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 x = 10 Output : 3 The pairs are (3, 7), (2, 8) and (4, 6). 1) Naive Approach: One by one get ea
15+ min read