710280. Sum of nodes within k distance from target

Medium

Sum of nodes within k distance from target

Summary

Given a tree and an integer k, find the sum of all nodes that are at most k distances away from a given target node. The problem requires traversing the tree, calculating the distances from each node to the target, and then summing up the values of nodes within the specified distance.

Detailed Explanation

The approach is to perform a level order traversal of the tree, keeping track of the current distance from the target node. For each node visited, check if its distance is less than or equal to k. If it is, add the node's value to the sum. To calculate the distance for each node, maintain a queue and push/pop nodes along with their distances.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty queue and set the target node as the current node.
  2. Perform a level order traversal of the tree, processing each node in the following way:
    • Dequeue the next node from the queue, along with its distance from the target.
    • If the distance is less than or equal to k, add the node's value to the sum.
    • Calculate the distances for all child nodes and enqueue them with their respective distances (i.e., incrementing the current distance by 1).
  3. Repeat step 2 until the queue is empty.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) { val = x; }
}

public class Main {
    public static int sumNodesWithinKDistance(TreeNode root, int target, int k) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int distance = 0;
        int sum = 0;

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (distance <= k) {
                sum += node.val;
            }

            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }

            distance++;
        }

        return sum;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.