Sum of all odd nodes in the path connecting two given nodes

Given a binary tree and two nodes of that binary tree. Find the sum of all nodes with odd values in the path connecting the two given nodes.
For Example: In the above binary tree, sum of all odd nodes in the path between the nodes andÂ
will be 5 + 1 + 3 = 9.
Source : Amazon Interview Experience on Campus
Approach : The idea is to first find the path between the two given nodes of the binary tree using the concept as discussed in: Print path between any two nodes.
Once, we have the path between the two given nodes, calculate sum of all the odd valued nodes in that path and print it.
Below is the implementation of the above approach:Â
C++
// C++ program to find sum of all odd nodes // in the path connecting two given nodesÂ
#include<bits/stdc++.h>using namespace std;Â
// Binary Tree nodestruct Node{Â Â Â Â int data;Â Â Â Â struct Node* left;Â Â Â Â struct Node* right;};Â
// Utility function to create a // new Binary Tree nodestruct Node* newNode(int data){Â Â Â Â struct Node* node = new Node;Â Â Â Â node->data = data;Â Â Â Â node->left = NULL;Â Â Â Â node->right = NULL;Â Â Â Â Â Â Â Â Â return node;}Â
// Function to check if there is a path from root // to the given node. It also populates // 'arr' with the given path bool getPath(Node* root, vector<int>& arr, int x) {     // if root is NULL     // there is no path     if (!root)         return false; Â
    // push the node's value in 'arr'     arr.push_back(root->data); Â
    // if it is the required node     // return true     if (root->data == x)         return true; Â
    // else check whether the required node lies     // in the left subtree or right subtree of     // the current node     if (getPath(root->left, arr, x) || getPath(root->right, arr, x))         return true; Â
    // required node does not lie either in the     // left or right subtree of the current node     // Thus, remove current node's value from     // 'arr'and then return false     arr.pop_back();     return false; } Â
// Function to get the sum of odd nodes in the // path between any two nodes in a binary tree int sumOddNodes(Node* root, int n1, int n2) {     // vector to store the path of     // first node n1 from root     vector<int> path1; Â
    // vector to store the path of     // second node n2 from root     vector<int> path2; Â
    getPath(root, path1, n1);     getPath(root, path2, n2); Â
    int intersection = -1; Â
    // Get intersection point     int i = 0, j = 0;     while (i != path1.size() || j != path2.size()) { Â
        // Keep moving forward until no intersection         // is found         if (i == j && path1[i] == path2[j]) {             i++;             j++;         }         else {             intersection = j - 1;             break;         }     }          int sum = 0;         // calculate sum of ODD nodes from the path     for (int i = path1.size() - 1; i > intersection; i--)         if(path1[i]%2)            sum += path1[i];Â
    for (int i = intersection; i < path2.size(); i++)         if(path2[i]%2)            sum += path2[i];                 return sum;       } Â
// Driver Codeint main(){Â Â Â Â struct Node* root = newNode(1);Â Â Â Â Â Â Â Â Â root->left = newNode(2);Â Â Â Â root->right = newNode(3);Â Â Â Â root->left->left = newNode(4);Â Â Â Â root->left->right = newNode(5);Â Â Â Â root->right->right = newNode(6);Â Â Â Â Â Â Â Â Â int node1 = 5; Â Â Â Â int node2 = 6; Â Â Â Â Â Â Â Â Â cout<<sumOddNodes(root, node1, node2); Â Â Â Â Â Â Â Â Â return 0;} |
Java
// Java program to find sum of all odd nodes // in the path connecting two given nodes Â
import java.util.*;class solution{Â
// Binary Tree node static class Node { Â Â Â Â int data; Â Â Â Â Â Node left; Â Â Â Â Â Node right; } Â
// Utility function to create a // new Binary Tree node  static Node newNode(int data) {      Node node = new Node();     node.data = data;     node.left = null;     node.right = null;          return node; } Â
// Function to check if there is a path from root // to the given node. It also populates // 'arr' with the given path static boolean getPath(Node root, Vector<Integer> arr, int x) {     // if root is null     // there is no path     if (root==null)         return false; Â
    // push the node's value in 'arr'     arr.add(root.data); Â
    // if it is the required node     // return true     if (root.data == x)         return true; Â
    // else check whether the required node lies     // in the left subtree or right subtree of     // the current node     if (getPath(root.left, arr, x) || getPath(root.right, arr, x))         return true; Â
    // required node does not lie either in the     // left or right subtree of the current node     // Thus, remove current node's value from     // 'arr'and then return false     arr.remove(arr.size()-1);     return false; } Â
// Function to get the sum of odd nodes in the // path between any two nodes in a binary tree static int sumOddNodes(Node root, int n1, int n2) {     // vector to store the path of     // first node n1 from root     Vector<Integer> path1= new Vector<Integer>(); Â
    // vector to store the path of     // second node n2 from root     Vector<Integer> path2= new Vector<Integer>(); Â
    getPath(root, path1, n1);     getPath(root, path2, n2); Â
    int intersection = -1; Â
    // Get intersection point     int i = 0, j = 0;     while (i != path1.size() || j != path2.size()) { Â
        // Keep moving forward until no intersection         // is found         if (i == j && path1.get(i) == path2.get(j)) {             i++;             j++;         }         else {             intersection = j - 1;             break;         }     }          int sum = 0;          // calculate sum of ODD nodes from the path     for (i = path1.size() - 1; i > intersection; i--)         if(path1.get(i)%2!=0)             sum += path1.get(i); Â
    for (i = intersection; i < path2.size(); i++)         if(path2.get(i)%2!=0)             sum += path2.get(i);                  return sum;        } Â
// Driver Code public static void main(String args[]) { Â Â Â Â Â Node root = newNode(1); Â Â Â Â Â Â Â Â Â root.left = newNode(2); Â Â Â Â root.right = newNode(3); Â Â Â Â root.left.left = newNode(4); Â Â Â Â root.left.right = newNode(5); Â Â Â Â root.right.right = newNode(6); Â Â Â Â Â Â Â Â Â int node1 = 5; Â Â Â Â int node2 = 6; Â Â Â Â Â Â Â Â Â System.out.print(sumOddNodes(root, node1, node2)); Â Â Â Â Â } } |
Python3
# Python3 program to find sum of all odd nodes # in the path connecting two given nodes Â
# Binary Tree node class Node:     def __init__(self):        self.data = 0        self.left = None        self.right = NoneÂ
# Utility function to create a # Binary Tree node def newNode( data): Â
    node = Node()     node.data = data     node.left = None    node.right = None         return node Â
# Function to check if there is a path from root # to the given node. It also populates # 'arr' with the given path def getPath(root, arr, x): Â
    # if root is None     # there is no path     if (root == None) :        return FalseÂ
    # push the node's value in 'arr'     arr.append(root.data) Â
    # if it is the required node     # return True     if (root.data == x) :        return TrueÂ
    # else check whether the required node lies     # in the left subtree or right subtree of     # the current node     if (getPath(root.left, arr, x) or getPath(root.right, arr, x)) :        return TrueÂ
    # required node does not lie either in the     # left or right subtree of the current node     # Thus, remove current node's value from     # 'arr'and then return False     arr.pop()     return FalseÂ
# Function to get the sum of odd nodes in the # path between any two nodes in a binary tree def sumOddNodes(root, n1, n2) :Â
    # vector to store the path of     # first node n1 from root     path1 = [] Â
    # vector to store the path of     # second node n2 from root     path2 = [] Â
    getPath(root, path1, n1)     getPath(root, path2, n2) Â
    intersection = -1Â
    # Get intersection point     i = 0    j = 0    while (i != len(path1) or j != len(path2)): Â
        # Keep moving forward until no intersection         # is found         if (i == j and path1[i] == path2[j]):             i = i + 1            j = j + 1                 else :            intersection = j - 1            break             sum = 0         i = len(path1) - 1         # calculate sum of ODD nodes from the path     while ( i > intersection ):         if(path1[i] % 2 != 0):             sum += path1[i]        i = i - 1             i = intersection    while ( i < len(path2) ):         if(path2[i] % 2 != 0) :            sum += path2[i]        i = i + 1                 return sum       Â
# Driver Code Â
root = newNode(1) Â Â Â Â Â root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) Â Â Â Â Â node1 = 5node2 = 6Â Â Â Â Â print(sumOddNodes(root, node1, node2)) Â
# This code is contributed by Arnab Kundu |
C#
// C# program to find sum of all odd nodes // in the path connecting two given nodes using System;using System.Collections.Generic;Â
class GFG{Â
// Binary Tree node public class Node { Â Â Â Â public int data; Â Â Â Â public Node left; Â Â Â Â public Node right; } Â
// Utility function to create a // new Binary Tree node static Node newNode(int data) { Â Â Â Â Node node = new Node(); Â Â Â Â node.data = data; Â Â Â Â node.left = null; Â Â Â Â node.right = null; Â Â Â Â Â Â Â Â Â return node; } Â
// Function to check if there is a path from // root to the given node. It also populates // 'arr' with the given path static Boolean getPath(Node root,                        List<int> arr, int x) {     // if root is null     // there is no path     if (root == null)         return false; Â
    // push the node's value in 'arr'     arr.Add(root.data); Â
    // if it is the required node     // return true     if (root.data == x)         return true; Â
    // else check whether the required node lies     // in the left subtree or right subtree of     // the current node     if (getPath(root.left, arr, x) ||         getPath(root.right, arr, x))         return true; Â
    // required node does not lie either in the     // left or right subtree of the current node     // Thus, Remove current node's value from     // 'arr'and then return false     arr.RemoveAt(arr.Count - 1);     return false; } Â
// Function to get the sum of odd nodes in the // path between any two nodes in a binary tree static int sumOddNodes(Node root, int n1, int n2) {     // List to store the path of     // first node n1 from root     List<int> path1 = new List<int>(); Â
    // List to store the path of     // second node n2 from root     List<int> path2 = new List<int>(); Â
    getPath(root, path1, n1);     getPath(root, path2, n2); Â
    int intersection = -1;Â
    // Get intersection point     int i = 0, j = 0;     while (i < path1.Count || j < path2.Count)    {                  // Keep moving forward until         // no intersection is found         if ( i == j && path1[i] == path2[j])        {             i++;             j++;         }         else        {             intersection = j - 1;             break;         }     }     int sum = 0;          // calculate sum of ODD nodes from the path     for (i = path1.Count - 1; i > intersection; i--)         if(path1[i] % 2 != 0)             sum += path1[i]; Â
    for (i = intersection; i < path2.Count; i++)         if(path2[i] % 2 != 0)             sum += path2[i];                  return sum;        } Â
// Driver Code public static void Main(String []args) { Â Â Â Â Node root = newNode(1); Â Â Â Â Â Â Â Â Â root.left = newNode(2); Â Â Â Â root.right = newNode(3); Â Â Â Â root.left.left = newNode(4); Â Â Â Â root.left.right = newNode(5); Â Â Â Â root.right.right = newNode(6); Â Â Â Â Â Â Â Â Â int node1 = 5; Â Â Â Â int node2 = 6; Â Â Â Â Â Â Â Â Â Console.Write(sumOddNodes(root, node1, node2)); } }Â
// This code is contributed by Arnub Kundu |
Javascript
<script>Â
    // JavaScript program to find sum of all odd nodes     // in the path connecting two given nodes          // Binary Tree node     class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }Â
    // Utility function to create a     // new Binary Tree node     function newNode(data)     {           let node = new Node(data);        return node;     } Â
    // Function to check if there is a path from root     // to the given node. It also populates     // 'arr' with the given path     function getPath(root, arr, x)     {         // if root is null         // there is no path         if (root==null)             return false; Â
        // push the node's value in 'arr'         arr.push(root.data); Â
        // if it is the required node         // return true         if (root.data == x)             return true; Â
        // else check whether the required node lies         // in the left subtree or right subtree of         // the current node         if (getPath(root.left, arr, x) || getPath(root.right, arr, x))             return true; Â
        // required node does not lie either in the         // left or right subtree of the current node         // Thus, remove current node's value from         // 'arr'and then return false         arr.pop();         return false;     } Â
    // Function to get the sum of odd nodes in the     // path between any two nodes in a binary tree     function sumOddNodes(root, n1, n2)     {         // vector to store the path of         // first node n1 from root         let path1= []; Â
        // vector to store the path of         // second node n2 from root         let path2= []; Â
        getPath(root, path1, n1);         getPath(root, path2, n2); Â
        let intersection = -1; Â
        // Get intersection point         let i = 0, j = 0;         while (i != path1.length || j != path2.length) { Â
            // Keep moving forward until no intersection             // is found             if (i == j && path1[i] == path2[j]) {                 i++;                 j++;             }             else {                 intersection = j - 1;                 break;             }         } Â
        let sum = 0; Â
        // calculate sum of ODD nodes from the path         for (i = path1.length - 1; i > intersection; i--)             if(path1[i]%2!=0)                 sum += path1[i]; Â
        for (i = intersection; i < path2.length; i++)             if(path2[i]%2!=0)                 sum += path2[i]; Â
        return sum;            }         let root = newNode(1);            root.left = newNode(2);     root.right = newNode(3);     root.left.left = newNode(4);     root.left.right = newNode(5);     root.right.right = newNode(6);            let node1 = 5;     let node2 = 6;            document.write(sumOddNodes(root, node1, node2)); Â
</script> |
Output
9
Complexity Analysis:
- Time Complexity : O(n)Â
- Auxiliary Space : O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



