Given a Binary Search Tree, a target node in the BST, and an integer value K, the task is to find the sum of all nodes that are at a distance K from the target node whose value is less than the target node.
Examples:
Input: target = 7, K = 2

Output: 11 Explanation: The nodes at a distance K(= 2) from the node 7 is 1, 4, and 6. Therefore, the sum of nodes is 11.
Input: target = 5, K = 1

Output: 4
Approach: The given problem can be solved by performing DFS Traversal for K distance below the target node and perform the DFS Traversal upward K distance from the target node. Follow the steps below to solve the problem:
- Define a function kDistanceDownSum(root, k, &sum) and perform the following steps:
- For the Base Case, check if the root is nullptr and k is less than 0, then return from the function.
- If the value of k equals 0, then add root->val to the variable sum and return.
- Call the same function kDistanceDownSum(root->left, k-1, sum) and kDistanceDownSum(root->right, k – 1, sum) for the left and right sub-trees.
- For the Base Case, check if the root is nullptr, then return -1.
- If the root is the same as the target, then call the function kDistanceDownSum(root->left, k – 1, sum) to calculate the sum for the first type of nodes and return 0(No second type of nodes possible).
- Initialize the variable dl as -1 and if the target is less than root, then set the value of dl as the value returned by the function kDistanceSum(root->left, target k, sum).
- If the value of dl is not equal to -1, then if sum equals (dl + 1), then add the value of root->data to the sum and then return -1.
- Similarly, initialize the variable dr as -1 and if the target is greater than the root, then update the value of dr to the value returned by kDistanceSum(root->right, target k, sum).
- If the value of dr is not equal to -1, then if the value of sum equals (dr + 1), then add the value of root->data to the sum. Otherwise, call the function kDistanceDownSum(root->left, k – dr – 2, sum) and return (1 + dr).
- After performing the above steps, print the value of ans as the resultant sum.
Following is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode( int data)
{
this ->data = data;
this ->left = NULL;
this ->right = NULL;
}
};
void kDistanceDownSum(TreeNode* root,
int k, int & sum)
{
if (root == NULL || k < 0)
return ;
if (k == 0) {
sum += root->data;
return ;
}
kDistanceDownSum(root->left,
k - 1, sum);
kDistanceDownSum(root->right,
k - 1, sum);
}
int kDistanceSum(TreeNode* root,
int target,
int k, int & sum)
{
if (root == NULL)
return -1;
if (root->data == target) {
kDistanceDownSum(root->left,
k - 1, sum);
return 0;
}
int dl = -1;
if (target < root->data) {
dl = kDistanceSum(root->left,
target, k, sum);
}
if (dl != -1) {
if (dl + 1 == k)
sum += root->data;
return -1;
}
int dr = -1;
if (target > root->data) {
dr = kDistanceSum(root->right,
target, k, sum);
}
if (dr != -1) {
if (dr + 1 == k)
sum += root->data;
else
kDistanceDownSum(root->left,
k - dr - 2, sum);
return 1 + dr;
}
return -1;
}
TreeNode* insertNode( int data,
TreeNode* root)
{
if (root == NULL) {
TreeNode* node = new TreeNode(data);
return node;
}
else if (data > root->data) {
root->right = insertNode(
data, root->right);
}
else if (data <= root->data) {
root->left = insertNode(
data, root->left);
}
return root;
}
void findSum(TreeNode* root, int target,
int K)
{
int sum = 0;
kDistanceSum(root, target, K, sum);
cout << sum;
}
int main()
{
TreeNode* root = NULL;
int N = 11;
int tree[] = { 3, 1, 7, 0, 2, 5,
10, 4, 6, 9, 8 };
for ( int i = 0; i < N; i++) {
root = insertNode(tree[i], root);
}
int target = 7;
int K = 2;
findSum(root, target, K);
return 0;
}
|
Java
import java.util.*;
public class GFG{
static int sum;
static class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
};
static void kDistanceDownSum(TreeNode root,
int k)
{
if (root == null || k < 0 )
return ;
if (k == 0 ) {
sum += root.data;
return ;
}
kDistanceDownSum(root.left,
k - 1 );
kDistanceDownSum(root.right,
k - 1 );
}
static int kDistanceSum(TreeNode root,
int target,
int k)
{
if (root == null )
return - 1 ;
if (root.data == target) {
kDistanceDownSum(root.left,
k - 1 );
return 0 ;
}
int dl = - 1 ;
if (target < root.data) {
dl = kDistanceSum(root.left,
target, k);
}
if (dl != - 1 ) {
if (dl + 1 == k)
sum += root.data;
return - 1 ;
}
int dr = - 1 ;
if (target > root.data) {
dr = kDistanceSum(root.right,
target, k);
}
if (dr != - 1 ) {
if (dr + 1 == k)
sum += root.data;
else
kDistanceDownSum(root.left,
k - dr - 2 );
return 1 + dr;
}
return - 1 ;
}
static TreeNode insertNode( int data,
TreeNode root)
{
if (root == null ) {
TreeNode node = new TreeNode(data);
return node;
}
else if (data > root.data) {
root.right = insertNode(
data, root.right);
}
else if (data <= root.data) {
root.left = insertNode(
data, root.left);
}
return root;
}
static void findSum(TreeNode root, int target,
int K)
{
sum = 0 ;
kDistanceSum(root, target, K);
System.out.print(sum);
}
public static void main(String[] args)
{
TreeNode root = null ;
int N = 11 ;
int tree[] = { 3 , 1 , 7 , 0 , 2 , 5 ,
10 , 4 , 6 , 9 , 8 };
for ( int i = 0 ; i < N; i++) {
root = insertNode(tree[i], root);
}
int target = 7 ;
int K = 2 ;
findSum(root, target, K);
}
}
|
Python3
sum = 0
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def kDistanceDownSum(root, k):
global sum
if (root = = None or k < 0 ):
return
if (k = = 0 ):
sum + = root.data
return
kDistanceDownSum(root.left,k - 1 )
kDistanceDownSum(root.right,k - 1 )
def kDistanceSum(root, target, k):
global sum
if (root = = None ):
return - 1
if (root.data = = target):
kDistanceDownSum(root.left,k - 1 )
return 0
dl = - 1
if (target < root.data):
dl = kDistanceSum(root.left, target, k)
if (dl ! = - 1 ):
if (dl + 1 = = k):
sum + = root.data
return - 1
dr = - 1
if (target > root.data):
dr = kDistanceSum(root.right, target, k)
if (dr ! = - 1 ):
if (dr + 1 = = k):
sum + = root.data
else :
kDistanceDownSum(root.left, k - dr - 2 )
return 1 + dr
return - 1
def insertNode(data, root):
if (root = = None ):
node = Node(data)
return node
elif (data > root.data):
root.right = insertNode(data, root.right)
elif (data < = root.data):
root.left = insertNode(data, root.left)
return root
def findSum(root, target, K):
kDistanceSum(root, target, K)
print ( sum )
if __name__ = = '__main__' :
root = None
N = 11
tree = [ 3 , 1 , 7 , 0 , 2 , 5 , 10 , 4 , 6 , 9 , 8 ]
for i in range (N):
root = insertNode(tree[i], root)
target = 7
K = 2
findSum(root, target, K)
|
C#
using System;
public class GFG{
static int sum;
public
class TreeNode {
public
int data;
public
TreeNode left;
public
TreeNode right;
public TreeNode( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
};
static void kDistanceDownSum(TreeNode root,
int k)
{
if (root == null || k < 0)
return ;
if (k == 0) {
sum += root.data;
return ;
}
kDistanceDownSum(root.left,
k - 1);
kDistanceDownSum(root.right,
k - 1);
}
static int kDistanceSum(TreeNode root,
int target,
int k)
{
if (root == null )
return -1;
if (root.data == target) {
kDistanceDownSum(root.left,
k - 1);
return 0;
}
int dl = -1;
if (target < root.data) {
dl = kDistanceSum(root.left,
target, k);
}
if (dl != -1) {
if (dl + 1 == k)
sum += root.data;
return -1;
}
int dr = -1;
if (target > root.data) {
dr = kDistanceSum(root.right,
target, k);
}
if (dr != -1) {
if (dr + 1 == k)
sum += root.data;
else
kDistanceDownSum(root.left,
k - dr - 2);
return 1 + dr;
}
return -1;
}
static TreeNode insertNode( int data,
TreeNode root)
{
if (root == null ) {
TreeNode node = new TreeNode(data);
return node;
}
else if (data > root.data) {
root.right = insertNode(
data, root.right);
}
else if (data <= root.data) {
root.left = insertNode(
data, root.left);
}
return root;
}
static void findSum(TreeNode root, int target,
int K)
{
sum = 0;
kDistanceSum(root, target, K);
Console.Write(sum);
}
public static void Main(String[] args)
{
TreeNode root = null ;
int N = 11;
int []tree = { 3, 1, 7, 0, 2, 5,
10, 4, 6, 9, 8 };
for ( int i = 0; i < N; i++) {
root = insertNode(tree[i], root);
}
int target = 7;
int K = 2;
findSum(root, target, K);
}
}
|
Javascript
<script>
let sum = 0;
class TreeNode {
constructor(data = "" , left = null , right = null ) {
this .data = data;
this .left = left;
this .right = right;
}
}
function kDistanceDownSum(root, k)
{
if (root == null || k < 0) {
return
}
if (k == 0) {
sum += root.data;
return ;
}
kDistanceDownSum(root.left, k - 1);
kDistanceDownSum(root.right, k - 1);
}
function kDistanceSum(root, target, k) {
if (root == null ) return -1;
if (root.data == target) {
kDistanceDownSum(root.left, k - 1);
return 0;
}
let dl = -1;
if (target < root.data) {
dl = kDistanceSum(root.left, target, k);
}
if (dl != -1) {
if (dl + 1 == k) sum += root.data;
return -1;
}
let dr = -1;
if (target > root.data) {
dr = kDistanceSum(root.right, target, k);
}
if (dr != -1) {
if (dr + 1 == k) sum += root.data;
else kDistanceDownSum(root.left, k - dr - 2);
return 1 + dr;
}
return -1;
}
function insertNode(data, root) {
if (root == null ) {
let node = new TreeNode(data);
return node;
}
else if (data > root.data) {
root.right = insertNode(data, root.right);
}
else if (data <= root.data) {
root.left = insertNode(data, root.left);
}
return root;
}
function findSum(root, target, K) {
kDistanceSum(root, target, K, sum);
document.write(sum);
}
let root = null ;
let N = 11;
let tree = [3, 1, 7, 0, 2, 5, 10, 4, 6, 9, 8];
for (let i = 0; i < N; i++) {
root = insertNode(tree[i], root);
}
let target = 7;
let K = 2;
findSum(root, target, K);
</script>
|
Time Complexity: O(N) where N is the number of nodes in given binary tree. Auxiliary Space: O(h) where h is the height of binary tree due to recursion call stack.
Approach using BFS:-
- We will be using level order traversal to find the sum of smaller value nodes
Implementation:-
- First we will find the target node using level order traversal.
- While finding the target node we will store the parent of each node so that we can move towards the parent of the node as well.
- After this we will traverse from the target node to all the tree directions that is toward both child and parent till distance K and add the values of node into our answer which are smaller than target at distance K.
C++
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode( int data)
{
this ->data = data;
this ->left = NULL;
this ->right = NULL;
}
};
TreeNode* insertNode( int data,
TreeNode* root)
{
if (root == NULL) {
TreeNode* node = new TreeNode(data);
return node;
}
else if (data > root->data) {
root->right = insertNode(
data, root->right);
}
else if (data <= root->data) {
root->left = insertNode(
data, root->left);
}
return root;
}
void findSum(TreeNode* root, int target,
int K)
{
int ans = 0;
queue<TreeNode*> q;
q.push(root);
TreeNode* need;
unordered_map<TreeNode*, TreeNode*> m;
while (q.size()){
int s = q.size();
for ( int i=0;i<s;i++){
TreeNode* temp = q.front();
q.pop();
if (temp->data==target) need=temp;
if (temp->left){
q.push(temp->left);
m[temp->left]=temp;
}
if (temp->right){
q.push(temp->right);
m[temp->right]=temp;
}
}
}
unordered_map<TreeNode*, int > mm;
q.push(need);
int c = 0;
while (q.size()){
int s = q.size();
for ( int i=0;i<s;i++){
TreeNode* temp = q.front();
q.pop();
mm[temp] = 1;
if (temp->data<target and c==K)
ans+=temp->data;
if (temp->left&&mm[temp->left]==0){
q.push(temp->left);
}
if (temp->right&&mm[temp->right]==0){
q.push(temp->right);
}
if (m[temp]&&mm[m[temp]]==0){
q.push(m[temp]);
}
}
c++;
if (c>K) break ;
}
cout<<ans<<endl;
}
int main()
{
TreeNode* root = NULL;
int N = 11;
int tree[] = { 3, 1, 7, 0, 2, 5,
10, 4, 6, 9, 8 };
for ( int i = 0; i < N; i++) {
root = insertNode(tree[i], root);
}
int target = 7;
int K = 2;
findSum(root, target, K);
return 0;
}
|
Java
import java.util.*;
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
public class Main {
public static TreeNode insertNode( int data,
TreeNode root)
{
if (root == null ) {
TreeNode node = new TreeNode(data);
return node;
}
else if (data > root.data) {
root.right = insertNode(
data, root.right);
}
else if (data <= root.data) {
root.left = insertNode(
data, root.left);
}
return root;
}
public static void findSum(TreeNode root, int target,
int K)
{
int ans = 0 ;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
TreeNode need = null ;
HashMap<TreeNode, TreeNode> m = new HashMap<>();
while (!q.isEmpty()) {
int s = q.size();
for ( int i = 0 ; i < s; i++) {
TreeNode temp = q.peek();
q.remove();
if (temp.data == target)
need = temp;
if (temp.left != null ) {
q.add(temp.left);
m.put(temp.left, temp);
}
if (temp.right != null ) {
q.add(temp.right);
m.put(temp.right, temp);
}
}
}
HashMap<TreeNode, Integer> mm = new HashMap<>();
q.add(need);
int c = 0 ;
while (!q.isEmpty()) {
int s = q.size();
for ( int i = 0 ; i < s; i++) {
TreeNode temp = q.peek();
q.remove();
mm.put(temp, 1 );
if (temp.data < target && c == K)
ans += temp.data;
if (temp.left != null && mm.getOrDefault(temp.left, 0 ) == 0 ) {
q.add(temp.left);
}
if (temp.right != null && mm.getOrDefault(temp.right, 0 ) == 0 ) {
q.add(temp.right);
}
if (m.get(temp) != null && mm.getOrDefault(m.get(temp), 0 ) == 0 ) {
q.add(m.get(temp));
}
}
c++;
if (c > K)
break ;
}
System.out.println(ans);
}
public static void main(String[] args)
{
TreeNode root = null ;
int N = 11 ;
int [] tree = { 3 , 1 , 7 , 0 , 2 , 5 , 10 , 4 , 6 , 9 , 8 };
for ( int i = 0 ; i < N; i++) {
root = insertNode(tree[i], root);
}
int target = 7 ;
int K = 2 ;
findSum(root, target, K);
}
}
|
Python
from collections import deque
class TreeNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def insertNode(data, root):
if root is None :
return TreeNode(data)
if data > root.data:
root.right = insertNode(data, root.right)
else :
root.left = insertNode(data, root.left)
return root
def findSum(root, target, K):
ans = 0
q = deque()
q.append(root)
need = None
m = {}
while q:
s = len (q)
for i in range (s):
temp = q.popleft()
if temp.data = = target:
need = temp
if temp.left:
q.append(temp.left)
m[temp.left] = temp
if temp.right:
q.append(temp.right)
m[temp.right] = temp
mm = {}
q.append(need)
c = 0
while q:
s = len (q)
for i in range (s):
temp = q.popleft()
mm[temp] = 1
if temp.data < target and c = = K:
ans + = temp.data
if temp.left and mm.get(temp.left, 0 ) = = 0 :
q.append(temp.left)
if temp.right and mm.get(temp.right, 0 ) = = 0 :
q.append(temp.right)
if temp in m and mm.get(m[temp], 0 ) = = 0 :
q.append(m[temp])
c + = 1
if c > K:
break
print (ans)
if __name__ = = "__main__" :
root = None
N = 11
tree = [ 3 , 1 , 7 , 0 , 2 , 5 , 10 , 4 , 6 , 9 , 8 ]
for i in range (N):
root = insertNode(tree[i], root)
target = 7
K = 2
findSum(root, target, K)
|
C#
using System;
using System.Collections.Generic;
namespace BinaryTreeKDistanceSum
{
class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
class Program
{
static TreeNode InsertNode( int data, TreeNode root)
{
if (root == null )
{
TreeNode node = new TreeNode(data);
return node;
}
else if (data > root.data)
{
root.right = InsertNode(data, root.right);
}
else if (data <= root.data)
{
root.left = InsertNode(data, root.left);
}
return root;
}
static void FindSum(TreeNode root, int target, int K)
{
int ans = 0;
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
TreeNode need = null ;
Dictionary<TreeNode, TreeNode> m = new Dictionary<TreeNode, TreeNode>();
while (q.Count > 0)
{
int s = q.Count;
for ( int i = 0; i < s; i++)
{
TreeNode temp = q.Dequeue();
if (temp.data == target) need = temp;
if (temp.left != null )
{
q.Enqueue(temp.left);
m[temp.left] = temp;
}
if (temp.right != null )
{
q.Enqueue(temp.right);
m[temp.right] = temp;
}
}
}
Dictionary<TreeNode, int > mm = new Dictionary<TreeNode, int >();
q.Enqueue(need);
int c = 0;
while (q.Count > 0)
{
int s = q.Count;
for ( int i = 0; i < s; i++)
{
TreeNode temp = q.Dequeue();
mm[temp] = 1;
if (temp.data < target && c == K)
{
ans += temp.data;
}
if (temp.left != null && !mm.ContainsKey(temp.left))
{
q.Enqueue(temp.left);
}
if (temp.right != null && !mm.ContainsKey(temp.right))
{
q.Enqueue(temp.right);
}
if (m.ContainsKey(temp) && !mm.ContainsKey(m[temp]))
{
q.Enqueue(m[temp]);
}
}
c++;
if (c > K) break ;
}
Console.WriteLine(ans);
}
static void Main( string [] args)
{
TreeNode root = null ;
int N = 11;
int [] tree = { 3, 1, 7, 0, 2, 5, 10, 4, 6, 9, 8 };
for ( int i = 0; i < N; i++)
{
root = InsertNode(tree[i], root);
}
int target = 7;
int K = 2;
FindSum(root, target, K);
}
}
}
|
Javascript
class TreeNode {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function insertNode(data, root) {
if (root === null ) {
const node = new TreeNode(data);
return node;
}
if (data > root.data) {
root.right = insertNode(data, root.right);
} else if (data <= root.data) {
root.left = insertNode(data, root.left);
}
return root;
}
function findSum(root, target, K) {
let ans = 0;
const queue = [root];
let need = null ;
const parentMap = new Map();
while (queue.length > 0) {
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const temp = queue.shift();
if (temp.data === target) {
need = temp;
}
if (temp.left !== null ) {
queue.push(temp.left);
parentMap.set(temp.left, temp);
}
if (temp.right !== null ) {
queue.push(temp.right);
parentMap.set(temp.right, temp);
}
}
}
const mm = new Map();
queue.push(need);
let distance = 0;
while (queue.length > 0) {
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const temp = queue.shift();
mm.set(temp, 1);
if (temp.data < target && distance === K) {
ans += temp.data;
}
if (temp.left !== null && mm.get(temp.left) !== 1) {
queue.push(temp.left);
}
if (temp.right !== null && mm.get(temp.right) !== 1) {
queue.push(temp.right);
}
if (parentMap.has(temp) && mm.get(parentMap.get(temp)) !== 1) {
queue.push(parentMap.get(temp));
}
}
distance++;
if (distance > K) {
break ;
}
}
console.log(ans);
}
function main() {
let root = null ;
const N = 11;
const tree = [3, 1, 7, 0, 2, 5, 10, 4, 6, 9, 8];
for (let i = 0; i < N; i++) {
root = insertNode(tree[i], root);
}
const target = 7;
const K = 2;
findSum(root, target, K);
}
main();
|
Time Complexity:- O(N) Auxiliary Space:- O(N)
|