Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum count of connected duplicate nodes in given N-ary Tree
Next article icon

Sum of nodes at maximum depth of a Binary Tree | Set 2

Last Updated : 15 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node.

Example: 

      1     /   \    2     3   / \   / \  4   5 6   7  Input : root(of above tree) Output : 22  Explanation: Nodes at maximum depth are: 4, 5, 6, 7.  So, sum of these nodes = 22

In the previous article we discussed a recursive solution which first finds the maximum level and then finds the sum of all nodes present at that level.
In this article we will see a recursive solution without finding the height or depth. The idea is that while traversing the nodes compare the level of the node with max_level (Maximum level till the current node). If the current level exceeds the maximum level, update the max_level as current level. If the max level and current level are same, add the root data to current sum otherwise if level is less than max_level, do nothing.

Below is the implementation of the above approach:

C++




// C++ Program to find sum of nodes at maximum
// Depth of the Binary Tree
 
#include <bits/stdc++.h>
using namespace std;
 
// Variables to store sum and
// maximum level
int sum = 0, max_level = INT_MIN;
 
// Binary Tree Node
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Utility function to create and
// return a new Binary Tree Node
Node* createNode(int val)
{
 
    Node* node = new Node;
 
    node->data = val;
    node->left = NULL;
    node->right = NULL;
 
    return node;
}
 
// Function to find the sum of the node which
// are present at the maximum depth
void sumOfNodesAtMaxDepth(Node* root, int level)
{
    if (root == NULL)
        return;
 
    // If the current level exceeds the
    // maximum level, update the max_level
    // as current level.
    if (level > max_level) {
        sum = root->data;
        max_level = level;
    }
 
    // If the max level and current level
    // are same, add the root data to
    // current sum.
    else if (level == max_level) {
        sum = sum + root->data;
    }
 
    // Traverse the left and right subtrees
    sumOfNodesAtMaxDepth(root->left, level + 1);
    sumOfNodesAtMaxDepth(root->right, level + 1);
}
 
// Driver Code
int main()
{
    Node* root;
    root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->left = createNode(6);
    root->right->right = createNode(7);
 
    sumOfNodesAtMaxDepth(root, 0);
 
    cout << sum;
 
    return 0;
}
 
 

Java




// Java Program to find sum of nodes at maximum
// Depth of the Binary Tree
 
class GfG
{
 
// Variables to store sum and
// maximum level
static int sum = 0,
    max_level = Integer.MIN_VALUE;
 
// Binary Tree Node
static class Node
{
    int data;
    Node left;
    Node right;
}
 
// Utility function to create and
// return a new Binary Tree Node
static Node createNode(int val)
{
 
    Node node = new Node();
    node.data = val;
    node.left = null;
    node.right = null;
 
    return node;
}
 
// Function to find the sum of
// the node which are present
// at the maximum depth
static void sumOfNodesAtMaxDepth(Node root,
                                int level)
{
    if (root == null)
        return;
 
    // If the current level exceeds the
    // maximum level, update the max_level
    // as current level.
    if (level > max_level)
    {
        sum = root.data;
        max_level = level;
    }
 
    // If the max level and current level
    // are same, add the root data to
    // current sum.
    else if (level == max_level)
    {
        sum = sum + root.data;
    }
 
    // Traverse the left and right subtrees
    sumOfNodesAtMaxDepth(root.left, level + 1);
    sumOfNodesAtMaxDepth(root.right, level + 1);
}
 
// Driver Code
public static void main(String[] args)
{
    Node root = null;
    root = createNode(1);
    root.left = createNode(2);
    root.right = createNode(3);
    root.left.left = createNode(4);
    root.left.right = createNode(5);
    root.right.left = createNode(6);
    root.right.right = createNode(7);
 
    sumOfNodesAtMaxDepth(root, 0);
    System.out.println(sum);
}
}
 
// This code is contributed by
// Prerna Saini.
 
 

Python3




# Python3 Program to find sum of nodes at maximum
# Depth of the Binary Tree
 
# Variables to store sum and
# maximum level
sum = [0]
max_level = [-(2**32)]
 
# Binary tree node
class createNode:
     
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to find the sum of the node which
# are present at the maximum depth
def sumOfNodesAtMaxDepth(root, level):
    if (root == None):
        return
     
    # If the current level exceeds the
    # maximum level, update the max_level
    # as current level.
    if (level > max_level[0]):
        sum[0] = root.data
        max_level[0] = level
         
    # If the max level and current level
    #are same, add the root data to
    # current sum.
    elif (level == max_level[0]):
        sum[0] = sum[0] + root.data
         
    # Traverse the left and right subtrees
    sumOfNodesAtMaxDepth(root.left, level + 1)
    sumOfNodesAtMaxDepth(root.right, level + 1)
     
# Driver Code
root = createNode(1)
root.left = createNode(2)
root.right = createNode(3)
root.left.left = createNode(4)
root.left.right = createNode(5)
root.right.left = createNode(6)
root.right.right = createNode(7)
 
sumOfNodesAtMaxDepth(root, 0)
 
print(sum[0])
 
# This code is contributed by SHUBHAMSINGH10
 
 

C#




// C#  Program to find sum of nodes at maximum
// Depth of the Binary Tree
using System;
public class GfG
{
 
    // Variables to store sum and
    // maximum level
    static int sum = 0,
        max_level = int.MinValue;
 
    // Binary Tree Node
    class Node
    {
        public int data;
        public Node left;
        public Node right;
    }
 
    // Utility function to create and
    // return a new Binary Tree Node
    static Node createNode(int val)
    {
 
        Node node = new Node();
        node.data = val;
        node.left = null;
        node.right = null;
 
        return node;
    }
 
    // Function to find the sum of
    // the node which are present
    // at the maximum depth
    static void sumOfNodesAtMaxDepth(Node root,
                                    int level)
    {
        if (root == null)
            return;
 
        // If the current level exceeds the
        // maximum level, update the max_level
        // as current level.
        if (level > max_level)
        {
            sum = root.data;
            max_level = level;
        }
 
        // If the max level and current level
        // are same, add the root data to
        // current sum.
        else if (level == max_level)
        {
            sum = sum + root.data;
        }
 
        // Traverse the left and right subtrees
        sumOfNodesAtMaxDepth(root.left, level + 1);
        sumOfNodesAtMaxDepth(root.right, level + 1);
    }
 
    // Driver Code
    public static void Main()
    {
        Node root = null;
        root = createNode(1);
        root.left = createNode(2);
        root.right = createNode(3);
        root.left.left = createNode(4);
        root.left.right = createNode(5);
        root.right.left = createNode(6);
        root.right.right = createNode(7);
 
        sumOfNodesAtMaxDepth(root, 0);
        Console.WriteLine(sum);
    }
}
 
/* This code is contributed PrinciRaj1992 */
 
 

Javascript




<script>
 
    // JavaScript Program to find sum of nodes at maximum
    // Depth of the Binary Tree
     
    // Variables to store sum and
    // maximum level
    let sum = 0;
    let max_level = Number.MIN_VALUE;
     
    // Binary Tree Node
    class Node
    {
        constructor(val) {
           this.left = null;
           this.right = null;
           this.data = val;
        }
    }
     
    // Utility function to create and
    // return a new Binary Tree Node
    function createNode(val)
    {
 
        let node = new Node(val);
        return node;
    }
 
    // Function to find the sum of
    // the node which are present
    // at the maximum depth
    function sumOfNodesAtMaxDepth(root, level)
    {
        if (root == null)
            return;
 
        // If the current level exceeds the
        // maximum level, update the max_level
        // as current level.
        if (level > max_level)
        {
            sum = root.data;
            max_level = level;
        }
 
        // If the max level and current level
        // are same, add the root data to
        // current sum.
        else if (level == max_level)
        {
            sum = sum + root.data;
        }
 
        // Traverse the left and right subtrees
        sumOfNodesAtMaxDepth(root.left, level + 1);
        sumOfNodesAtMaxDepth(root.right, level + 1);
    }
     
    let root = null;
    root = createNode(1);
    root.left = createNode(2);
    root.right = createNode(3);
    root.left.left = createNode(4);
    root.left.right = createNode(5);
    root.right.left = createNode(6);
    root.right.right = createNode(7);
   
    sumOfNodesAtMaxDepth(root, 0);
    document.write(sum);
 
</script>
 
 
Output
22

Complexity Analysis:

  • Time Complexity: O(N) where N is the number of vertices in the binary tree.
  • Auxiliary Space: O(N).  


Next Article
Maximum count of connected duplicate nodes in given N-ary Tree

A

Ashwin Loganathan
Improve
Article Tags :
  • C++ Programs
  • Data Structures
  • DSA
  • Recursion
  • Tree
Practice Tags :
  • Data Structures
  • Recursion
  • Tree

Similar Reads

  • Sum of all the levels in a Binary Search Tree
    Given a Binary Search Tree, the task is to find the horizontal sum of the nodes that are at the same level.Examples: Input: Output: 6 12 24Input: Output: 6 12 12 Approach DFS: Find the height of the given binary tree then the number of levels in the tree will be levels = height + 1. Now create an ar
    15+ min read
  • Sum of the mirror image nodes of a complete binary tree in an inorder way
    Given a complete binary tree, the task is to find the sum of mirror image nodes in an inorder way i.e. find the inorder traversal of the left sub-tree and for every node traversed, add the value of its mirror node to the current node's value. Examples: Input: Output: 20 51 19 10 Inorder traversal of
    6 min read
  • Print nodes in top view of Binary Tree | Set 2
    Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
    14 min read
  • Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
    Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node
    12 min read
  • Maximum count of connected duplicate nodes in given N-ary Tree
    Given a generic tree such that each node has a value associated with it, the task is to find the largest number of connected nodes having the same value in the tree. Two nodes are connected if one node is a child of another node. Example: Input: Tree in the image below Output: 4 Explanation: The lar
    10 min read
  • Determine the count of Leaf nodes in an N-ary tree
    Given the value of 'N' and 'I'. Here, [Tex]I [/Tex]represents the number of internal nodes present in an N-ary tree and every node of the N-ary can either have [Tex]N [/Tex]childs or zero child. The task is to determine the number of Leaf nodes in n-ary tree. Examples: Input : N = 3, I = 5 Output :
    4 min read
  • Floor in Binary Search Tree (BST)
    Given a Binary Search Tree and a number x, the task is to find the floor of x in the given BST, where floor means the greatest value node of the BST which is smaller than or equal to x. if x is smaller than the smallest node of BST then return -1. Examples: Input: Output: 55Explanantion: Table of Co
    14 min read
  • Euler Tour | Subtree Sum using Segment Tree
    Euler tour tree (ETT) is a method for representing a rooted tree as a number sequence. When traversing the tree using Depth for search(DFS), insert each node in a vector twice, once while entered it and next after visiting all its children. This method is very useful for solving subtree problems and
    15+ min read
  • Sum of nodes at maximum depth of a Binary Tree
    Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 While traversing the nodes compare th
    15+ min read
  • Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
    Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from the root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7Input : root(of above tree)Output : 22Explanation:Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22Approach: There exists a recursive
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences