Sum of distances of all nodes from a given node
Last Updated :
14 Jun, 2022
Given a Binary Tree and an integer target, denoting the value of a node, the task is to find the sum of distances of all nodes from the given node.
Examples:
Input: target = 3

Output: 19
Explanation:

Distance of Nodes 1, 6, 7 from the Node 3 = 1
Distance of the Node 2 from the Node 3 = 2
Distance of the Nodes 4, 5 from the Node 3 = 3
Distance of the Nodes 8, 9 from the Node 3 = 4
Sum of the distances = (1 + 1 + 1) + (2) + (3 + 3) + (4 + 4) = 19.
Input: target = 4

Output: 18
Naive Approach: The simplest idea to solve this problem is that, whenever a node is traversed on the left or right of a node, then the distances of the nodes their subtrees reduces by 1, and distance of the rest of the nodes from that node increases by 1.
Therefore, the following relation gives the sum of distances of all nodes from a node, say u:
sumDists(u)= sumDists(parent(u)) - (Nodes in the left and right subtree of u) + (N - Nodes in the left and right subtree of u)
where,
sumDists(u): Sum of distances of all nodes from the node u
sumDists(parent(u)): Sum of distances of all nodes from the parent node of u
Follow the steps below to solve the problem:
- Create a function to find the number of nodes in the left and right subtree of the given node(including the given node).
- Create a function to find the sum of depths of the node and variable sum denotes the sum of the distance of all nodes from the target.
- Traverse the tree using DFS(Depth First Search) and for each node perform the following:
- If the target matches with the current node then update sum as distance.
- Else:
- If root->left is not null, Find the number of nodes in the left subtree and pass the sum of the distance of all nodes from the root->left node as tempSum.
- If root->right is not null, Find the number of nodes in the right subtree and pass the sum of the distance of all nodes from the root->rightnode as tempSum.
- On reaching the target node, print the sum of the distance of nodes from the target node.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a
// Binary Tree Node
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
};
// Function that allocates a new node
// with the given data and NULL to its
// left and right pointers
TreeNode* newNode(int data)
{
// Allocate the node
TreeNode* Node = new TreeNode();
// Allocate Memory
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
// Function which calculates sum
// of depths of all nodes
int sumofdepth(TreeNode* root, int l)
{
// Base Case
if (root == NULL)
return 0;
// Return recursively
return l + sumofdepth(root->left,
l + 1)
+ sumofdepth(root->right,
l + 1);
}
// Function to count of nodes
// in the left and right subtree
int Noofnodes(TreeNode* root)
{
// Base Case
if (root == NULL)
return 0;
// Return recursively
return Noofnodes(root->left)
+ Noofnodes(root->right)
+ 1;
}
// Stores the sum of distances
// of all nodes from given node
int sum = 0;
// Function to find sum of distances
// of all nodes from a given node
void distance(TreeNode* root,
int target,
int distancesum,
int n)
{
// If target node matches
// with the current node
if (root->data == target) {
sum = distancesum;
return;
}
// If left of current node exists
if (root->left) {
// Count number of nodes
// in the left subtree
int nodes = Noofnodes(
root->left);
// Update sum
int tempsum = distancesum
- nodes
+ (n - nodes);
// Recur for the left subtree
distance(root->left, target,
tempsum, n);
}
// If right is not null
if (root->right) {
// Find number of nodes
// in the left subtree
int nodes = Noofnodes(
root->right);
// Applying the formula given
// in the approach
int tempsum = distancesum
- nodes + (n - nodes);
// Recur for the right subtree
distance(root->right, target,
tempsum, n);
}
}
// Driver Code
int main()
{
// Input 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 target = 3;
// Sum of depth of all
// nodes from root node
int distanceroot
= sumofdepth(root, 0);
// Number of nodes in the
// left and right subtree
int totalnodes = Noofnodes(root);
distance(root, target, distanceroot,
totalnodes);
// Print the sum of distances
cout << sum;
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Structure of a
// Binary Tree Node
static class TreeNode
{
int data;
TreeNode left, right;
}
// Function that allocates a new node
// with the given data and NULL to its
// left and right pointers
static TreeNode newNode(int data)
{
TreeNode Node = new TreeNode();
Node.data = data;
Node.left = Node.right = null;
return (Node);
}
// Function which calculates sum
// of depths of all nodes
static int sumofdepth(TreeNode root, int l)
{
// Base Case
if (root == null)
return 0;
// Return recursively
return l + sumofdepth(root.left, l + 1) +
sumofdepth(root.right, l + 1);
}
// Function to count of nodes
// in the left and right subtree
static int Noofnodes(TreeNode root)
{
// Base Case
if (root == null)
return 0;
// Return recursively
return Noofnodes(root.left) +
Noofnodes(root.right) + 1;
}
// Stores the sum of distances
// of all nodes from given node
public static int sum = 0;
// Function to find sum of distances
// of all nodes from a given node
static void distance(TreeNode root, int target,
int distancesum, int n)
{
// If target node matches
// with the current node
if (root.data == target)
{
sum = distancesum;
return;
}
// If left of current node exists
if (root.left != null)
{
// Count number of nodes
// in the left subtree
int nodes = Noofnodes(root.left);
// Update sum
int tempsum = distancesum - nodes +
(n - nodes);
// Recur for the left subtree
distance(root.left, target, tempsum, n);
}
// If right is not null
if (root.right != null)
{
// Find number of nodes
// in the left subtree
int nodes = Noofnodes(root.right);
// Applying the formula given
// in the approach
int tempsum = distancesum - nodes +
(n - nodes);
// Recur for the right subtree
distance(root.right, target, tempsum, n);
}
}
// Driver Code
public static void main(String[] args)
{
// Input 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 target = 3;
// Sum of depth of all
// nodes from root node
int distanceroot = sumofdepth(root, 0);
// Number of nodes in the
// left and right subtree
int totalnodes = Noofnodes(root);
distance(root, target, distanceroot,
totalnodes);
// Print the sum of distances
System.out.println(sum);
}
}
// This code is contributed by Dharanendra L V
Python3
# Python3 program for the above approach
# Structure of a
# Binary Tree Node
class TreeNode:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function which calculates sum
# of depths of all nodes
def sumofdepth(root, l):
# Base Case
if (root == None):
return 0
# Return recursively
return l + sumofdepth(root.left, l + 1)+ sumofdepth(root.right, l + 1)
# Function to count of nodes
# in the left and right subtree
def Noofnodes(root):
# Base Case
if (root == None):
return 0
# Return recursively
return Noofnodes(root.left) + Noofnodes(root.right) + 1
# Stores the sum of distances
# of all nodes from given node
sum = 0
# Function to find sum of distances
# of all nodes from a given node
def distance(root, target, distancesum, n):
global sum
# If target node matches
# with the current node
if (root.data == target):
sum = distancesum
return
# If left of current node exists
if (root.left):
# Count number of nodes
# in the left subtree
nodes = Noofnodes(root.left)
# Update sum
tempsum = distancesum - nodes + (n - nodes)
# Recur for the left subtree
distance(root.left, target, tempsum, n)
# If right is not null
if (root.right):
# Find number of nodes
# in the left subtree
nodes = Noofnodes(root.right)
# Applying the formula given
# in the approach
tempsum = distancesum - nodes + (n - nodes)
# Recur for the right subtree
distance(root.right, target, tempsum, n)
# Driver Code
if __name__ == '__main__':
# Input tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
root.left.left.left = TreeNode(8)
root.left.left.right = TreeNode(9)
target = 3
# Sum of depth of all
# nodes from root node
distanceroot = sumofdepth(root, 0)
# Number of nodes in the
# left and right subtree
totalnodes = Noofnodes(root)
distance(root, target, distanceroot, totalnodes)
# Print the sum of distances
print (sum)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
public class GFG{
// Structure of a
// Binary Tree Node
class TreeNode
{
public int data;
public TreeNode left, right;
}
// Function that allocates a new node
// with the given data and NULL to its
// left and right pointers
static TreeNode newNode(int data)
{
TreeNode Node = new TreeNode();
Node.data = data;
Node.left = Node.right = null;
return (Node);
}
// Function which calculates sum
// of depths of all nodes
static int sumofdepth(TreeNode root, int l)
{
// Base Case
if (root == null)
return 0;
// Return recursively
return l + sumofdepth(root.left, l + 1) +
sumofdepth(root.right, l + 1);
}
// Function to count of nodes
// in the left and right subtree
static int Noofnodes(TreeNode root)
{
// Base Case
if (root == null)
return 0;
// Return recursively
return Noofnodes(root.left) +
Noofnodes(root.right) + 1;
}
// Stores the sum of distances
// of all nodes from given node
public static int sum = 0;
// Function to find sum of distances
// of all nodes from a given node
static void distance(TreeNode root, int target,
int distancesum, int n)
{
// If target node matches
// with the current node
if (root.data == target)
{
sum = distancesum;
return;
}
// If left of current node exists
if (root.left != null)
{
// Count number of nodes
// in the left subtree
int nodes = Noofnodes(root.left);
// Update sum
int tempsum = distancesum - nodes +
(n - nodes);
// Recur for the left subtree
distance(root.left, target, tempsum, n);
}
// If right is not null
if (root.right != null)
{
// Find number of nodes
// in the left subtree
int nodes = Noofnodes(root.right);
// Applying the formula given
// in the approach
int tempsum = distancesum - nodes +
(n - nodes);
// Recur for the right subtree
distance(root.right, target, tempsum, n);
}
}
// Driver Code
public static void Main(String[] args)
{
// Input 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 target = 3;
// Sum of depth of all
// nodes from root node
int distanceroot = sumofdepth(root, 0);
// Number of nodes in the
// left and right subtree
int totalnodes = Noofnodes(root);
distance(root, target, distanceroot,
totalnodes);
// Print the sum of distances
Console.WriteLine(sum);
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program for the above approach
// Structure of a
// Binary Tree Node
class TreeNode
{
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// Function that allocates a new node
// with the given data and NULL to its
// left and right pointers
function newNode(data)
{
let Node = new TreeNode(data);
return (Node);
}
// Function which calculates sum
// of depths of all nodes
function sumofdepth(root, l)
{
// Base Case
if (root == null)
return 0;
// Return recursively
return l + sumofdepth(root.left, l + 1) +
sumofdepth(root.right, l + 1);
}
// Function to count of nodes
// in the left and right subtree
function Noofnodes(root)
{
// Base Case
if (root == null)
return 0;
// Return recursively
return Noofnodes(root.left) +
Noofnodes(root.right) + 1;
}
// Stores the sum of distances
// of all nodes from given node
let sum = 0;
// Function to find sum of distances
// of all nodes from a given node
function distance(root, target, distancesum, n)
{
// If target node matches
// with the current node
if (root.data == target)
{
sum = distancesum;
return;
}
// If left of current node exists
if (root.left != null)
{
// Count number of nodes
// in the left subtree
let nodes = Noofnodes(root.left);
// Update sum
let tempsum = distancesum - nodes + (n - nodes);
// Recur for the left subtree
distance(root.left, target, tempsum, n);
}
// If right is not null
if (root.right != null)
{
// Find number of nodes
// in the left subtree
let nodes = Noofnodes(root.right);
// Applying the formula given
// in the approach
let tempsum = distancesum - nodes + (n - nodes);
// Recur for the right subtree
distance(root.right, target, tempsum, n);
}
}
// Input tree
let 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);
let target = 3;
// Sum of depth of all
// nodes from root node
let distanceroot = sumofdepth(root, 0);
// Number of nodes in the
// left and right subtree
let totalnodes = Noofnodes(root);
distance(root, target, distanceroot,
totalnodes);
// Print the sum of distances
document.write(sum);
// This code is contributed by suresh07.
</script>
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by adding an extra variable, say size, to denote the count of nodes in its left and the right subtrees, in the structure of a node. This reduces the task of calculating the size of subtrees to constant computational time
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a
// binary tree node
class TreeNode {
public:
int data, size;
TreeNode* left;
TreeNode* right;
};
// Function that allocates a new node
// with the given data and NULL to
// its left and right pointers
TreeNode* newNode(int data)
{
TreeNode* Node = new TreeNode();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
// Return newly created node
return (Node);
}
// Function to count the number of
// nodes in the left and right subtrees
pair<int, int> sumofsubtree(TreeNode* root)
{
// Initialize a pair that stores
// the pair {number of nodes, depth}
pair<int, int> p = make_pair(1, 0);
// Finding the number of nodes
// in the left subtree
if (root->left) {
pair<int, int> ptemp
= sumofsubtree(root->left);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Find the number of nodes
// in the right subtree
if (root->right) {
pair<int, int> ptemp
= sumofsubtree(root->right);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Filling up size field
root->size = p.first;
return p;
}
// Stores the sum of distances of all
// nodes from the given node
int sum = 0;
// Function to find the total distance
void distance(TreeNode* root, int target,
int distancesum, int n)
{
// If target node matches with
// the current node
if (root->data == target) {
sum = distancesum;
}
// If root->left is not null
if (root->left) {
// Update sum
int tempsum = distancesum
- root->left->size
+ (n - root->left->size);
// Recur for the left subtree
distance(root->left, target,
tempsum, n);
}
// If root->right is not null
if (root->right) {
// Apply the formula given
// in the approach
int tempsum = distancesum
- root->right->size
+ (n - root->right->size);
// Recur for the right subtree
distance(root->right, target,
tempsum, n);
}
}
// Driver Code
int main()
{
// Input 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 target = 3;
pair<int, int> p = sumofsubtree(root);
// Total number of nodes
int totalnodes = p.first;
distance(root, target, p.second,
totalnodes);
// Print the sum of distances
cout << sum << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
static class pair
{
int first, second;
public pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
// Structure of a
// binary tree node
static class TreeNode
{
int data, size;
TreeNode left;
TreeNode right;
};
// Function that allocates a new node
// with the given data and null to
// its left and right pointers
static TreeNode newNode(int data)
{
TreeNode Node = new TreeNode();
Node.data = data;
Node.left = null;
Node.right = null;
// Return newly created node
return (Node);
}
// Function to count the number of
// nodes in the left and right subtrees
static pair sumofsubtree(TreeNode root)
{
// Initialize a pair that stores
// the pair {number of nodes, depth}
pair p = new pair(1, 0);
// Finding the number of nodes
// in the left subtree
if (root.left != null)
{
pair ptemp
= sumofsubtree(root.left);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Find the number of nodes
// in the right subtree
if (root.right != null)
{
pair ptemp
= sumofsubtree(root.right);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Filling up size field
root.size = p.first;
return p;
}
// Stores the sum of distances of all
// nodes from the given node
static int sum = 0;
// Function to find the total distance
static void distance(TreeNode root, int target,
int distancesum, int n)
{
// If target node matches with
// the current node
if (root.data == target)
{
sum = distancesum;
}
// If root.left is not null
if (root.left != null)
{
// Update sum
int tempsum = distancesum
- root.left.size
+ (n - root.left.size);
// Recur for the left subtree
distance(root.left, target,
tempsum, n);
}
// If root.right is not null
if (root.right != null)
{
// Apply the formula given
// in the approach
int tempsum = distancesum
- root.right.size
+ (n - root.right.size);
// Recur for the right subtree
distance(root.right, target,
tempsum, n);
}
}
// Driver Code
public static void main(String[] args)
{
// Input 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 target = 3;
pair p = sumofsubtree(root);
// Total number of nodes
int totalnodes = p.first;
distance(root, target, p.second,
totalnodes);
// Print the sum of distances
System.out.print(sum +"\n");
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program for the above approach
# Stores the sum of distances of all
# nodes from the given node
sum = 0
# Structure of a
# binary tree node
class TreeNode:
def __init__(self, data):
self.data = data
self.size = 0
self.left = None
self.right = None
# Function to count the number of
# nodes in the left and right subtrees
def sumofsubtree(root):
# Initialize a pair that stores
# the pair {number of nodes, depth}
p = [1, 0]
# Finding the number of nodes
# in the left subtree
if (root.left):
ptemp = sumofsubtree(root.left)
p[1] += ptemp[0] + ptemp[1]
p[0] += ptemp[0]
# Find the number of nodes
# in the right subtree
if (root.right):
ptemp = sumofsubtree(root.right)
p[1] += ptemp[0] + ptemp[1]
p[0] += ptemp[0]
# Filling up size field
root.size = p[0]
return p
# Function to find the total distance
def distance(root, target, distancesum, n):
global sum
# If target node matches with
# the current node
if (root.data == target):
sum = distancesum
# If root.left is not null
if (root.left):
# Update sum
tempsum = (distancesum - root.left.size +
(n - root.left.size))
# Recur for the left subtree
distance(root.left, target, tempsum, n)
# If root.right is not null
if (root.right):
# Apply the formula given
# in the approach
tempsum = (distancesum - root.right.size +
(n - root.right.size))
# Recur for the right subtree
distance(root.right, target, tempsum, n)
# Driver Code
if __name__ == '__main__':
# Input tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
root.left.left.left = TreeNode(8)
root.left.left.right = TreeNode(9)
target = 3
p = sumofsubtree(root)
# Total number of nodes
totalnodes = p[0]
distance(root, target, p[1], totalnodes)
# Print the sum of distances
print(sum)
# This code is contributed by ipg2016107
C#
// C# program for the above approach
using System;
public class GFG
{
class pair
{
public int first, second;
public pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
// Structure of a
// binary tree node
class TreeNode
{
public int data, size;
public TreeNode left;
public TreeNode right;
};
// Function that allocates a new node
// with the given data and null to
// its left and right pointers
static TreeNode newNode(int data)
{
TreeNode Node = new TreeNode();
Node.data = data;
Node.left = null;
Node.right = null;
// Return newly created node
return (Node);
}
// Function to count the number of
// nodes in the left and right subtrees
static pair sumofsubtree(TreeNode root)
{
// Initialize a pair that stores
// the pair {number of nodes, depth}
pair p = new pair(1, 0);
// Finding the number of nodes
// in the left subtree
if (root.left != null)
{
pair ptemp
= sumofsubtree(root.left);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Find the number of nodes
// in the right subtree
if (root.right != null)
{
pair ptemp
= sumofsubtree(root.right);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Filling up size field
root.size = p.first;
return p;
}
// Stores the sum of distances of all
// nodes from the given node
static int sum = 0;
// Function to find the total distance
static void distance(TreeNode root, int target,
int distancesum, int n)
{
// If target node matches with
// the current node
if (root.data == target)
{
sum = distancesum;
}
// If root.left is not null
if (root.left != null)
{
// Update sum
int tempsum = distancesum
- root.left.size
+ (n - root.left.size);
// Recur for the left subtree
distance(root.left, target,
tempsum, n);
}
// If root.right is not null
if (root.right != null)
{
// Apply the formula given
// in the approach
int tempsum = distancesum
- root.right.size
+ (n - root.right.size);
// Recur for the right subtree
distance(root.right, target,
tempsum, n);
}
}
// Driver Code
public static void Main(String[] args)
{
// Input 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 target = 3;
pair p = sumofsubtree(root);
// Total number of nodes
int totalnodes = p.first;
distance(root, target, p.second,
totalnodes);
// Print the sum of distances
Console.Write(sum +"\n");
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program for the above approach
class pair
{
constructor(first,second)
{
this.first = first;
this.second = second;
}
}
// Structure of a
// binary tree node
class Node
{
// Function that allocates a new node
// with the given data and null to
// its left and right pointers
constructor(data)
{
this.data=data;
this.size=0;
this.left=this.right=null;
}
}
// Function to count the number of
// nodes in the left and right subtrees
function sumofsubtree(root)
{
// Initialize a pair that stores
// the pair {number of nodes, depth}
let p = new pair(1, 0);
// Finding the number of nodes
// in the left subtree
if (root.left != null)
{
let ptemp
= sumofsubtree(root.left);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Find the number of nodes
// in the right subtree
if (root.right != null)
{
let ptemp
= sumofsubtree(root.right);
p.second += ptemp.first
+ ptemp.second;
p.first += ptemp.first;
}
// Filling up size field
root.size = p.first;
return p;
}
// Stores the sum of distances of all
// nodes from the given node
let sum = 0;
// Function to find the total distance
function distance(root,target,distancesum,n)
{
// If target node matches with
// the current node
if (root.data == target)
{
sum = distancesum;
}
// If root.left is not null
if (root.left != null)
{
// Update sum
let tempsum = distancesum
- root.left.size
+ (n - root.left.size);
// Recur for the left subtree
distance(root.left, target,
tempsum, n);
}
// If root.right is not null
if (root.right != null)
{
// Apply the formula given
// in the approach
let tempsum = distancesum
- root.right.size
+ (n - root.right.size);
// Recur for the right subtree
distance(root.right, target,
tempsum, n);
}
}
// Driver Code
// Input tree
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.left.left.left = new Node(8);
root.left.left.right = new Node(9);
let target = 3;
let p = sumofsubtree(root);
// Total number of nodes
let totalnodes = p.first;
distance(root, target, p.second,
totalnodes);
// Print the sum of distances
document.write(sum +"<br>");
// This code is contributed by unknown2108
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read