Odd level sum of given Binary Tree
Last Updated :
16 Nov, 2023
Given a binary tree, write a function that takes the root node and updates the original tree in such a way every node that is present at an odd level gets updated as the sum of the node's value and its grandparent's value.
Examples:
Input: Consider a binary tree having values {3, 2, 5, 1, 4, NULL, 7}.
3 Level 1
/ \
2 5 Level 2
/ \ \
1 4 7 Level 3
Output:
3 Level 1
/ \
2 5 Level 2
/ \ \
4 7 10 Level 3
Explanation: A first odd level that has grand parent is level 3 and for updating 3rd level's nodes we add 3 to their respective values as 3 is their grandparent. (1 + 3 = 4 , 4 + 3 = 7 and 3 + 7 = 10)
Approach: To solve the problem follow the below idea:
The idea is to traverse the children of current node recursively and maintain the track of grand parent and the current level using a boolean (where true represents odd level and false represents even level )so whenever we reach a odd level then update the node's value and continue doing same for the rest of the remaining nodes.
Below code represent above approach in C++ .
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
// Function to tranform tree as
void helper(Node* root, int val, bool flag)
{
if (flag) {
int temp = root->data;
root->data += val;
val = temp;
if (root->left != NULL)
helper(root->left, val, !flag);
if (root->right != NULL)
helper(root->right, val, !flag);
}
else {
if (root->left != NULL)
helper(root->left, val, !flag);
if (root->right != NULL)
helper(root->right, val, !flag);
}
}
// Iterative method to find height of Binary Tree
void printLevelOrder(Node* root)
{
// Base Case
if (root == NULL)
return;
// Create an empty queue for
// level order traversal
queue<Node*> q;
// Enqueue Root and initialize height
q.push(root);
while (q.empty() == false) {
// Print front of queue and
// remove it from queue
Node* node = q.front();
cout << node->data << " ";
q.pop();
// Enqueue left child
if (node->left != NULL)
q.push(node->left);
// Enqueue right child
if (node->right != NULL)
q.push(node->right);
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown
// in above diagram
Node* root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
root->right->right = newNode(7);
cout << "Level Order traversal of binary tree without "
"transformation \n";
// Function call
printLevelOrder(root);
helper(root, 0, true);
cout << "\nLevel Order traversal of binary tree after "
"transformation \n";
// Function call
printLevelOrder(root);
return 0;
}
Java
// Java code for the above approach
import java.util.LinkedList;
import java.util.Queue;
// A Binary Tree Node
class Node {
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
}
class GFG {
// Method to transform tree
static void helper(Node root, int val, boolean flag)
{
if (flag) {
int temp = root.data;
root.data += val;
val = temp;
if (root.left != null)
helper(root.left, val, !flag);
if (root.right != null)
helper(root.right, val, !flag);
}
else {
if (root.left != null)
helper(root.left, val, !flag);
if (root.right != null)
helper(root.right, val, !flag);
}
}
// Iterative method to find height of Binary Tree
static void printLevelOrder(Node root)
{
// Base case
if (root == null)
return;
// Create an empty queue for
// level order traversal
Queue<Node> q = new LinkedList<>();
// Enqueue Root and initialize height
q.add(root);
while (!q.isEmpty()) {
// Print front of queue and
// remove it from queue
Node node = q.poll();
System.out.print(node.data + " ");
// Enqueue left child
if (node.left != null)
q.add(node.left);
// Enqueue right child
if (node.right != null)
q.add(node.right);
}
}
// Main method
public static void main(String[] args)
{
// Create binary tree as shown
// in above diagram
Node root = new Node(3);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.right.right = new Node(7);
System.out.println(
"Level Order traversal of binary tree without transformation:");
printLevelOrder(root);
// Call the method
helper(root, 0, true);
System.out.println(
"\nLevel Order traversal of binary tree after transformation:");
printLevelOrder(root);
}
}
// This code is contributed by Abhinav Mahajan (abhinav_m22)
Python3
from queue import Queue
# A Binary Tree Node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to transform the tree
def helper(root, val, flag):
if flag:
temp = root.data
root.data += val
val = temp
if root.left is not None:
helper(root.left, val, not flag)
if root.right is not None:
helper(root.right, val, not flag)
else:
if root.left is not None:
helper(root.left, val, not flag)
if root.right is not None:
helper(root.right, val, not flag)
# Iterative method to find height of Binary Tree
def printLevelOrder(root):
# Base Case
if root is None:
return
# Create an empty queue for level order traversal
q = Queue()
# Enqueue Root and initialize height
q.put(root)
while not q.empty():
# Print front of the queue and remove it from the queue
node = q.get()
print(node.data, end=" ")
# Enqueue left child
if node.left is not None:
q.put(node.left)
# Enqueue right child
if node.right is not None:
q.put(node.right)
# Utility function to create a new tree node
def newNode(data):
temp = Node(data)
temp.left = temp.right = None
return temp
# Driver program to test the functions
if __name__ == "__main__":
# Let us create the binary tree shown in the C++ code
root = newNode(3)
root.left = newNode(2)
root.right = newNode(5)
root.left.left = newNode(1)
root.left.right = newNode(4)
root.right.right = newNode(7)
print("Level Order traversal of binary tree without transformation:")
# Function call
printLevelOrder(root)
helper(root, 0, True)
print("\nLevel Order traversal of binary tree after transformation:")
# Function call
printLevelOrder(root)
C#
using System;
using System.Collections.Generic;
// A Binary Tree Node
class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
class GFG
{
// Method to transform tree
static void Helper(Node root, ref int val, bool flag)
{
if (flag)
{
int temp = root.data;
root.data += val;
val = temp;
if (root.left != null)
Helper(root.left, ref val, !flag);
if (root.right != null)
Helper(root.right, ref val, !flag);
}
else
{
if (root.left != null)
Helper(root.left, ref val, !flag);
if (root.right != null)
Helper(root.right, ref val, !flag);
}
}
// Iterative method to find level order traversal of Binary Tree
static void PrintLevelOrder(Node root)
{
// Base case
if (root == null)
return;
// Create an empty queue for
// level order traversal
Queue<Node> q = new Queue<Node>();
// Enqueue Root
q.Enqueue(root);
while (q.Count > 0)
{
// Print front of queue and
// Dequeue it
Node node = q.Dequeue();
Console.Write(node.data + " ");
// Enqueue left child
if (node.left != null)
q.Enqueue(node.left);
// Enqueue right child
if (node.right != null)
q.Enqueue(node.right);
}
}
// Main method
public static void Main(string[] args)
{
// Create binary tree as shown in Java code
Node root = new Node(3);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.right.right = new Node(7);
Console.WriteLine("Level Order traversal of binary tree without transformation:");
PrintLevelOrder(root);
int val = 0;
Helper(root, ref val, true);
Console.WriteLine("\nLevel Order traversal of binary tree after transformation:");
PrintLevelOrder(root);
}
}
JavaScript
// Javascript code for the above approach
// A Binary Tree Node
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class GFG {
// Function to tranform tree as
static helper(root, val, flag) {
if (flag) {
const temp = root.data;
root.data += val;
val = temp;
if (root.left !== null)
GFG.helper(root.left, val, !flag);
if (root.right !== null)
GFG.helper(root.right, val, !flag);
} else {
if (root.left !== null)
GFG.helper(root.left, val, !flag);
if (root.right !== null)
GFG.helper(root.right, val, !flag);
}
}
static printLevelOrder(root) {
if (root === null)
return;
const queue = [];
queue.push(root);
while (queue.length > 0) {
const node = queue.shift();
process.stdout.write(node.data + ' ');
if (node.left !== null)
queue.push(node.left);
if (node.right !== null)
queue.push(node.right);
}
}
static main() {
const root = new Node(3);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.right.right = new Node(7);
console.log("Level Order traversal of binary tree without transformation:");
GFG.printLevelOrder(root);
let val = 0;
GFG.helper(root, val, true);
console.log("\nLevel Order traversal of binary tree after transformation:");
GFG.printLevelOrder(root);
}
}
GFG.main();
OutputLevel Order traversal of binary tree without transformation
3 2 5 1 4 7
Level Order traversal of binary tree after transformation
3 2 5 4 7 10
Time Complexity: O(N)
Auxiliary Space: O(H)
Similar Reads
Sum of all nodes in a binary tree Give an algorithm for finding the sum of all elements in a binary tree. In the above binary tree sum = 106. Recommended PracticeSum of Binary TreeTry It!The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data. Implementation: C++ /* Program to
15+ min read
Find sum of all left leaves in a given Binary Tree Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then a
15+ min read
Diagonal Sum of a Binary Tree Consider lines of slope -1 passing between nodes (dotted lines in below diagram). The diagonal sum in a binary tree is the sum of all node's data lying between these lines. Given a Binary Tree, print all diagonal sums. For the following input tree, the output should be 9, 19, 42. 9 is sum of 1, 3 an
15+ min read
Sink Odd nodes in Binary Tree Given a Binary Tree having odd and even elements, sink all its odd valued nodes such that no node with odd value could be parent of node with even value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note that a node with even
13 min read
Find maximum level sum in Binary Tree Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6Output: 6Explanation :Sum of all nodes of 0'th level is 4Sum of all nodes of 1'th level is -3Sum of all nodes of 0'th level is 6Hence maximum sum is 6
15+ min read
Sum of all leaf nodes of binary tree Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
5 min read