Open In App

Odd level sum of given Binary Tree

Last Updated : 16 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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();


Output

Level 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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads