Given a binary tree consisting of N nodes, the task is to find the sum of depths of all subtree nodes in a given binary tree.
Examples:
Input:
Output: 26
Explanation:
The leaf nodes having value 8, 9, 5, 6, and 7 have the sum of subtree depths equal to 0.
Node 4 has a total of 2 nodes in its subtree, both in the same level. Therefore, sum of subtree depth is equal to 2.
Node 2 has a total of 4 nodes in its subtree, 2 in each level. Therefore, the sum of subtree depth is equal to 6.
Node 3 has a total of 2 nodes in its subtree, both at the same level. Therefore, the sum of subtree depth is equal to 2.
Node 1 has a total of 8 nodes in its subtree, 2 in the first level, 4 in the 2nd level, and 2 in the last. Therefore, sum of subtree depths is equal to 16.
Therefore, the total sum of all subtree depths is equal to 2 + 6 + 2 + 16 = 26Input:
Output: 5
Naive Approach: The simplest approach is to traverse the tree and for every node, calculate the sum of depths of all nodes from that node recursively and print the final sum obtained.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Binary tree nodeclass TreeNode {public: int data; TreeNode* left; TreeNode* right;};// Function that allocates a new// node with data and NULL to its// left and right pointersTreeNode* newNode(int data){ TreeNode* Node = new TreeNode(); Node->data = data; Node->left = NULL; Node->right = NULL; // Return the node return (Node);}// Function to find the sum of depths of// all nodes in subtree of the current nodeint sumofdepth(TreeNode* root, int d){ // IF NULL node then return 0 if (root == NULL) return 0; // Recursivly find the sum of // depths of all nodes in the // left and right subtree return d + sumofdepth(root->left, d + 1) + sumofdepth(root->right, d + 1);}// Function to calculate the sum// of depth of all the subtreesint sumofallsubtrees(TreeNode* root){ // if root is NULL return 0 if (root == NULL) return 0; // Find the total depth sum of // current node and recursively return sumofdepth(root, 0) + sumofallsubtrees(root->left) + sumofallsubtrees(root->right);}// Driver Codeint main(){ // Given Tree TreeNode* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); // Function Call cout << sumofallsubtrees(root); return 0;} |
Java
// Java program for the above approachclass GFG{// Binary tree nodestatic class TreeNode{ int data; TreeNode left, right;}// Function that allocates a new// node with data and NULL to its// left and right pointersstatic TreeNode newNode(int data){ TreeNode Node = new TreeNode(); Node.data = data; Node.left = Node.right = null; return (Node);}// Function to find the sum of depths of// all nodes in subtree of the current nodestatic int sumofdepth(TreeNode root, int d){ // If NULL node then return 0 if (root == null) return 0; // Recursivly find the sum of // depths of all nodes in the // left and right subtree return d + sumofdepth(root.left, d + 1) + sumofdepth(root.right, d + 1);}// Function to calculate the sum// of depth of all the subtreesstatic int sumofallsubtrees(TreeNode root){ // If root is NULL return 0 if (root == null) return 0; // Find the total depth sum of // current node and recursively return sumofdepth(root, 0) + sumofallsubtrees(root.left) + sumofallsubtrees(root.right);}// Driver Codepublic static void main(String[] args){ // Given Tree TreeNode root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); // Function Call System.out.println(sumofallsubtrees(root));}}// This code is contributed by Dharanendra L V |
26
Time complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized based on the following observations:
Suppose X and Y are the number of nodes in left and right subtrees respectively and S1 and S2 are the sum of depths of nodes in left and right subtrees.
Then, the sum of depths of the current node can be calculated as S1 + S2 + x + y, where depths of x + y nodes increase by 1.
Follow the steps below to solve the problem:
- Define a recursive DFS function say sumofsubtree(root) as:
- Initialize a pair p which stores the total nodes in the current nodes subtree and the total sum of depths of all node in the current subtree
- Check if the left child is not NULL and then recursively call the function sumoftree(root->left) and increment the p.first by the total number of nodes in the left subtree and increment the p.second by the total sum of depths for all node in the left subtree.
- Check if the right child is not NULL and then recursively call the function sumoftree(root->right) and increment the p.first by the total number of nodes in the right subtree and increment the p.second by the total sum of depths for all node in the right subtree.
- Increment the total ans by p.second and return pair p.
- Call the DFS function sumoftree(root) and print the result obtained ans.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Binary tree nodeclass TreeNode {public: int data; TreeNode* left; TreeNode* right;};// Function to allocate a new// node with the given data and// NULL in its left and right pointersTreeNode* newNode(int data){ TreeNode* Node = new TreeNode(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);}// DFS function to calculate the sum// of depths of all subtrees depth sumpair<int, int> sumofsubtree(TreeNode* root, int& ans){ // Store total number of node in // its subtree and total sum of // depth in its subtree pair<int, int> p = make_pair(1, 0); // Check if left is not NULL if (root->left) { // Call recursively the DFS // function for left child pair<int, int> ptemp = sumofsubtree(root->left, ans); // Increment the sum of depths // by ptemp.first+p.temp.first p.second += ptemp.first + ptemp.second; // Increment p.fisrt by count // of noded in left subtree p.first += ptemp.first; } // Check if right is not NULL if (root->right) { // Call recursively the DFS // function for right child pair<int, int> ptemp = sumofsubtree(root->right, ans); // Increment the sum of depths // by ptemp.first+p.temp.first p.second += ptemp.first + ptemp.second; // Increment p.fisrt by count of // nodes in right subtree p.first += ptemp.first; } // Increment the result by total // sum of depth in current subtree ans += p.second; // Return p return p;}// Driver Codeint main(){ // Given Tree TreeNode* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); int ans = 0; sumofsubtree(root, ans); // Print the result cout << ans; return 0;} |
26
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.





