Print all nodes at distance k from a given node

Last Updated : 18 Aug, 2026

Given the root of a binary tree, the value of a target node, and an integer k, return all the nodes that are exactly k edges away from the target node. Return the node values in sorted order.

Note:

  • All node values are unique.
  • The target node is guaranteed to be present in the tree.

Examples:

Input: root = [1, 2, 3, 4, 5],target = 2, k = 2

Binary-tree-to-string-with-brackets

Output: 3
Explanation: Nodes at a distance 2 from the given target node 2 is 3.

Input: root = [1, 2, 3, 4, 5, 6, 7], target = 3, k = 1

1

Output: 1 6 7
Explanation: Nodes at a distance 1 from the given target node 3 are 1 , 6 and 7.

Try It Yourself
redirect icon

[Naive Approach] Find Distance of Every Node from Target - O(nÂē) Time and O(h) Space

The idea is to traverse the binary tree and for each node, find its distance from the target.

To find the distance between current node and target, we first find LCA of both and use the LCA.

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Find the LCA of two nodes.
Node* lca(Node* root, int a, int b) {
    if (root == nullptr || root->data == a || root->data == b)
        return root;

    Node* left = lca(root->left, a, b);
    Node* right = lca(root->right, a, b);

    if (left && right)
        return root;

    return left ? left : right;
}

// Find distance of a node from the root.
int findDist(Node* root, int target) {
    if (root == nullptr)
        return -1;

    if (root->data == target)
        return 0;

    int left = findDist(root->left, target);

    if (left != -1)
        return left + 1;

    int right = findDist(root->right, target);

    if (right != -1)
        return right + 1;

    return -1;
}

// Find distance between two nodes.
int distance(Node* root, int a, int b) {
    Node* ancestor = lca(root, a, b);

    int d1 = findDist(ancestor, a);
    int d2 = findDist(ancestor, b);

    return d1 + d2;
}

void solve(Node* root, Node* treeRoot, int target, int k,
           vector<int>& ans) {
    if (root == nullptr)
        return;

    // Check if current node is at distance k from target.
    if (distance(treeRoot, root->data, target) == k)
        ans.push_back(root->data);

    solve(root->left, treeRoot, target, k, ans);
    solve(root->right, treeRoot, target, k, ans);
}

vector<int> kDistanceNodes(Node* root, int target, int k) {
    vector<int> ans;

    solve(root, root, target, k, ans);

    // Sort the result.
    sort(ans.begin(), ans.end());

    return ans;
}

int main() {
    // Create the binary tree:
    //       1
    //      / \
    //     2   3
    //    / \
    //   4   5

    Node* 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);

    int target = 2;
    int k = 2;

    vector<int> ans = kDistanceNodes(root, target, k);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // Find the LCA of two nodes.
    static Node lca(Node root, int a, int b) {
        if (root == null || root.data == a || root.data == b)
            return root;

        Node left = lca(root.left, a, b);
        Node right = lca(root.right, a, b);

        if (left != null && right != null)
            return root;

        return left != null ? left : right;
    }

    // Find distance of a node from the root.
    static int findDist(Node root, int target) {
        if (root == null)
            return -1;

        if (root.data == target)
            return 0;

        int left = findDist(root.left, target);

        if (left != -1)
            return left + 1;

        int right = findDist(root.right, target);

        if (right != -1)
            return right + 1;

        return -1;
    }

    // Find distance between two nodes.
    static int distance(Node root, int a, int b) {
        Node ancestor = lca(root, a, b);

        int d1 = findDist(ancestor, a);
        int d2 = findDist(ancestor, b);

        return d1 + d2;
    }

    static void solve(Node root, Node treeRoot, int target, int k,
                      ArrayList<Integer> ans) {
        if (root == null)
            return;

        // Check if current node is at distance k from target.
        if (distance(treeRoot, root.data, target) == k)
            ans.add(root.data);

        solve(root.left, treeRoot, target, k, ans);
        solve(root.right, treeRoot, target, k, ans);
    }

    static ArrayList<Integer> kDistanceNodes(Node root, int target, int k) {
        ArrayList<Integer> ans = new ArrayList<>();

        solve(root, root, target, k, ans);

        // Sort the result.
        Collections.sort(ans);

        return ans;
    }

    public static void main(String[] args) {
        // Create the binary tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5

        Node 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);

        int target = 2;
        int k = 2;

        ArrayList<Integer> ans = kDistanceNodes(root, target, k);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# Find the LCA of two nodes.
def lca(root, a, b):
    if root is None or root.data == a or root.data == b:
        return root

    left = lca(root.left, a, b)
    right = lca(root.right, a, b)

    if left and right:
        return root

    return left if left else right


# Find distance of a node from the root.
def findDist(root, target):
    if root is None:
        return -1

    if root.data == target:
        return 0

    left = findDist(root.left, target)

    if left != -1:
        return left + 1

    right = findDist(root.right, target)

    if right != -1:
        return right + 1

    return -1


# Find distance between two nodes.
def distance(root, a, b):
    ancestor = lca(root, a, b)

    d1 = findDist(ancestor, a)
    d2 = findDist(ancestor, b)

    return d1 + d2


def solve(root, treeRoot, target, k, ans):
    if root is None:
        return

    # Check if current node is at distance k from target.
    if distance(treeRoot, root.data, target) == k:
        ans.append(root.data)

    solve(root.left, treeRoot, target, k, ans)
    solve(root.right, treeRoot, target, k, ans)


def kDistanceNodes(root, target, k):
    ans = []

    solve(root, root, target, k, ans)

    # Sort the result.
    ans.sort()

    return ans


if __name__ == "__main__":
    # Create the binary tree:
    #       1
    #      / \
    #     2   3
    #    / \
    #   4   5

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    target = 2
    k = 2

    ans = kDistanceNodes(root, target, k)

    for x in ans:
        print(x, end=" ")
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {

    // Find the LCA of two nodes.
    static Node lca(Node root, int a, int b) {
        if (root == null || root.data == a || root.data == b)
            return root;

        Node left = lca(root.left, a, b);
        Node right = lca(root.right, a, b);

        if (left != null && right != null)
            return root;

        return left != null ? left : right;
    }

    // Find distance of a node from the root.
    static int findDist(Node root, int target) {
        if (root == null)
            return -1;

        if (root.data == target)
            return 0;

        int left = findDist(root.left, target);

        if (left != -1)
            return left + 1;

        int right = findDist(root.right, target);

        if (right != -1)
            return right + 1;

        return -1;
    }

    // Find distance between two nodes.
    static int distance(Node root, int a, int b) {
        Node ancestor = lca(root, a, b);

        int d1 = findDist(ancestor, a);
        int d2 = findDist(ancestor, b);

        return d1 + d2;
    }

    static void solve(Node root, Node treeRoot, int target, int k,
               List<int> ans) {
        if (root == null)
            return;

        // Check if current node is at distance k from target.
        if (distance(treeRoot, root.data, target) == k)
            ans.Add(root.data);

        solve(root.left, treeRoot, target, k, ans);
        solve(root.right, treeRoot, target, k, ans);
    }

    public static  List<int> kDistanceNodes(Node root, int target, int k) {
        List<int> ans = new List<int>();

        solve(root, root, target, k, ans);

        // Sort the result.
        ans.Sort();

        return ans;
    }

  public static void Main() {
        // Create the binary tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5

        Node 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);

        int target = 2;
        int k = 2;

        List<int> ans = kDistanceNodes(root, target, k);

        foreach (int x in ans)
            Console.Write(x + " ");
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Find the LCA of two nodes.
function lca(root, a, b)
{
    if (root === null || root.data === a || root.data === b)
        return root;

    let left = lca(root.left, a, b);
    let right = lca(root.right, a, b);

    if (left && right)
        return root;

    return left ? left : right;
}

// Find distance of a node from the root.
function findDist(root, target)
{
    if (root === null)
        return -1;

    if (root.data === target)
        return 0;

    let left = findDist(root.left, target);

    if (left !== -1)
        return left + 1;

    let right = findDist(root.right, target);

    if (right !== -1)
        return right + 1;

    return -1;
}

// Find distance between two nodes.
function distance(root, a, b)
{
    let ancestor = lca(root, a, b);

    let d1 = findDist(ancestor, a);
    let d2 = findDist(ancestor, b);

    return d1 + d2;
}

function solve(root, treeRoot, target, k, ans)
{
    if (root === null)
        return;

    // Check if current node is at distance k from target.
    if (distance(treeRoot, root.data, target) === k)
        ans.push(root.data);

    solve(root.left, treeRoot, target, k, ans);
    solve(root.right, treeRoot, target, k, ans);
}

function kDistanceNodes(root, target, k)
{
    let ans = [];

    solve(root, root, target, k, ans);

    // Sort the result.
    ans.sort((a, b) => a - b);

    return ans;
}

// Driver code
// Create the binary tree:
//       1
//      / \
    //     2   3
//    / \
    //   4   5

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);

let target = 2;
let k = 2;

let ans = kDistanceNodes(root, target, k);

for (let x of ans)
    process.stdout.write(x + " ");

Output
3 

[Expected Approach - 1] Using Recursion - O(n log n) Time and O(h) Space

The idea is to traverse the binary tree using recursion to find the target node. Once the target is found, find all nodes at distance k in its left and right subtrees.

While returning through the path from the target to the root, check the opposite subtree (if target is present in left, then check right and vice versa) of each ancestor for nodes at the remaining distance, which is k - distance - 1.

Suppose the target is present in the left subtree of the current node:

frame_3226

To reach a node in the right subtree from the target:

  • Distance edges are used to reach the current node from the target.
  • One more edge is used to move from the current node to the right subtree.

Therefore, the remaining distance to search in the right subtree is: k - distance - 1

Similarly, if the target is present in the right subtree, we search the left subtree at distance k - distance - 1.

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Find nodes at a given distance from root.
void findNodes(Node* root, int dis, vector<int>& ans) {
    if (root == nullptr)
        return;

    if (dis == 0) {
        ans.push_back(root->data);
        return;
    }

    findNodes(root->left, dis - 1, ans);
    findNodes(root->right, dis - 1, ans);
}

// Find the distance of target from the current node.
int kDistanceRecur(Node* root, int target, int k,
                   vector<int>& ans) {
    if (root == nullptr)
        return -1;

    // If current node is target.
    if (root->data == target) {
        findNodes(root, k, ans);
        return 1;
    }

    int left = kDistanceRecur(root->left, target, k, ans);

    // Target is present in the left subtree.
    if (left != -1) {
        if (k - left == 0)
            ans.push_back(root->data);
        else
            findNodes(root->right, k - left - 1, ans);

        return left + 1;
    }

    int right = kDistanceRecur(root->right, target, k, ans);

    // Target is present in the right subtree.
    if (right != -1) {
        if (k - right == 0)
            ans.push_back(root->data);
        else
            findNodes(root->left, k - right - 1, ans);

        return right + 1;
    }

    return -1;
}

vector<int> kDistanceNodes(Node* root, int target, int k) {
    vector<int> ans;

    kDistanceRecur(root, target, k, ans);

    // Sort the result.
    sort(ans.begin(), ans.end());

    return ans;
}

int main() {
    // Create the binary tree:
    //       1
    //      / \
    //     2   3
    //    / \
    //   4   5

    Node* 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);

    int target = 2;
    int k = 2;

    vector<int> ans = kDistanceNodes(root, target, k);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {

    // Find nodes at a given distance from root.
    static void findNodes(Node root, int dis, ArrayList<Integer> ans) {
        if (root == null)
            return;

        if (dis == 0) {
            ans.add(root.data);
            return;
        }

        findNodes(root.left, dis - 1, ans);
        findNodes(root.right, dis - 1, ans);
    }

    // Find the distance of target from the current node.
    static int kDistanceRecur(Node root, int target, int k,
                              ArrayList<Integer> ans) {
        if (root == null)
            return -1;

        // If current node is target.
        if (root.data == target) {
            findNodes(root, k, ans);
            return 1;
        }

        int left = kDistanceRecur(root.left, target, k, ans);

        // Target is present in the left subtree.
        if (left != -1) {
            if (k - left == 0)
                ans.add(root.data);
            else
                findNodes(root.right, k - left - 1, ans);

            return left + 1;
        }

        int right = kDistanceRecur(root.right, target, k, ans);

        // Target is present in the right subtree.
        if (right != -1) {
            if (k - right == 0)
                ans.add(root.data);
            else
                findNodes(root.left, k - right - 1, ans);

            return right + 1;
        }

        return -1;
    }

    static ArrayList<Integer> kDistanceNodes(Node root, int target, int k) {
        ArrayList<Integer> ans = new ArrayList<>();

        kDistanceRecur(root, target, k, ans);

        // Sort the result.
        Collections.sort(ans);

        return ans;
    }

    public static void main(String[] args) {
        // Create the binary tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5

        Node 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);

        int target = 2;
        int k = 2;

        ArrayList<Integer> ans = kDistanceNodes(root, target, k);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
# Structure of Binary Tree Node
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# Find nodes at a given distance from root.
def findNodes(root, dis, ans):
    if root is None or dis < 0:
        return

    if dis == 0:
        ans.append(root.data)
        return

    findNodes(root.left, dis - 1, ans)
    findNodes(root.right, dis - 1, ans)


# Find the distance of target from the current node.
def kDistanceRecur(root, target, k, ans):
    if root is None:
        return -1

    # If current node is target.
    if root.data == target:
        findNodes(root, k, ans)
        return 1

    left = kDistanceRecur(root.left, target, k, ans)

    # Target is present in the left subtree.
    if left != -1:
        if k - left == 0:
            ans.append(root.data)
        else:
            findNodes(root.right, k - left - 1, ans)

        return left + 1

    right = kDistanceRecur(root.right, target, k, ans)

    # Target is present in the right subtree.
    if right != -1:
        if k - right == 0:
            ans.append(root.data)
        else:
            findNodes(root.left, k - right - 1, ans)

        return right + 1

    return -1


def kDistanceNodes(root, target, k):
    ans = []

    kDistanceRecur(root, target, k, ans)

    # Sort the result.
    ans.sort()

    return ans


if __name__ == "__main__":

    # Create the binary tree:
    #       1
    #      / \
    #     2   3
    #    / \
    #   4   5

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    target = 2
    k = 2

    ans = kDistanceNodes(root, target, k)

    for x in ans:
        print(x, end=" ")
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {

    // Find nodes at a given distance from root.
    static void findNodes(Node root, int dis, List<int> ans) {
        if (root == null)
            return;

        if (dis == 0) {
            ans.Add(root.data);
            return;
        }

        findNodes(root.left, dis - 1, ans);
        findNodes(root.right, dis - 1, ans);
    }

    // Find the distance of target from the current node.
    static int kDistanceRecur(Node root, int target, int k,
                              List<int> ans) {
        if (root == null)
            return -1;

        // If current node is target.
        if (root.data == target) {
            findNodes(root, k, ans);
            return 1;
        }

        int left = kDistanceRecur(root.left, target, k, ans);

        // Target is present in the left subtree.
        if (left != -1) {
            if (k - left == 0)
                ans.Add(root.data);
            else
                findNodes(root.right, k - left - 1, ans);

            return left + 1;
        }

        int right = kDistanceRecur(root.right, target, k, ans);

        // Target is present in the right subtree.
        if (right != -1) {
            if (k - right == 0)
                ans.Add(root.data);
            else
                findNodes(root.left, k - right - 1, ans);

            return right + 1;
        }

        return -1;
    }

    static List<int> kDistanceNodes(Node root, int target, int k) {
        List<int> ans = new List<int>();

        kDistanceRecur(root, target, k, ans);

        // Sort the result.
        ans.Sort();

        return ans;
    }

    static void Main() {
        // Create the binary tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5

        Node 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);

        int target = 2;
        int k = 2;

        List<int> ans = kDistanceNodes(root, target, k);

        foreach (int x in ans)
            Console.Write(x + " ");
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Find nodes at a given distance from root.
function findNodes(root, dis, ans)
{
    if (root === null)
        return;

    if (dis === 0) {
        ans.push(root.data);
        return;
    }

    findNodes(root.left, dis - 1, ans);
    findNodes(root.right, dis - 1, ans);
}

// Find the distance of target from the current node.
function kDistanceRecur(root, target, k, ans)
{
    if (root === null)
        return -1;

    // If current node is target.
    if (root.data === target) {
        findNodes(root, k, ans);
        return 1;
    }

    let left = kDistanceRecur(root.left, target, k, ans);

    // Target is present in the left subtree.
    if (left !== -1) {
        if (k - left === 0)
            ans.push(root.data);
        else
            findNodes(root.right, k - left - 1, ans);

        return left + 1;
    }

    let right = kDistanceRecur(root.right, target, k, ans);

    // Target is present in the right subtree.
    if (right !== -1) {
        if (k - right === 0)
            ans.push(root.data);
        else
            findNodes(root.left, k - right - 1, ans);

        return right + 1;
    }

    return -1;
}

function kDistanceNodes(root, target, k)
{
    let ans = [];

    kDistanceRecur(root, target, k, ans);

    // Sort the result.
    ans.sort((a, b) => a - b);

    return ans;
}

// Driver code
// Create the binary tree:
//       1
//      / \
    //     2   3
//    / \
    //   4   5

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);

let target = 2;
let k = 2;

let ans = kDistanceNodes(root, target, k);

for (let x of ans)
    process.stdout.write(x + " ");

Output
3 

[Expected Approach - 2] Using BFS with Parent Mapping - O(n log n) Time and O(n) Space

The idea is to store the parent of every node in a hash map so that we can move from the target node in all three directions: left child, right child, and parent. Then, perform Breadth First Search (BFS) from the target to find all nodes at distance k.

Note that we can do DFS as well once we have the parent mapping.

In a binary tree, we can normally move only from a node to its children. Therefore, a node outside the target's subtree cannot be reached directly.

Consider:

Binary-tree-to-string-with-brackets

To make this upward movement possible, store the parent of every node:

  • 4 -> 2
  • 5 -> 2
  • 2 -> 1
  • 3 -> 1

Now, from any node, we can move to its left child, right child, or parent.

  • Start BFS from the target node with distance 0.
  • Move to the left child, right child, and parent.
  • Keep track of visited nodes to avoid visiting the same node again.
  • Process the tree level by level and increase the distance after each level.
  • When the distance becomes k, the nodes in the queue are exactly k edges away from the target.
  • Finally, sort the result.
C+
#include <bits/stdc++.h>
using namespace std;

// Structure of Binary Tree Node
class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

unordered_map<Node*, Node*> par;

// Build the parent mapping and locate the target node
Node* markParents(Node* root, int target) {
    Node* tar = nullptr;

    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        Node* cur = q.front();
        q.pop();

        if (cur->data == target)
            tar = cur;

        if (cur->left) {
            par[cur->left] = cur;
            q.push(cur->left);
        }

        if (cur->right) {
            par[cur->right] = cur;
            q.push(cur->right);
        }
    }

    return tar;
}

// Find nodes at distance k using BFS
vector<int> kDistanceNodes(Node* root, int target, int k) {
    vector<int> ans;

    // Build the parent mapping and find the target node
    Node* tar = markParents(root, target);

    unordered_set<Node*> vis;
    queue<Node*> q;

    q.push(tar);
    vis.insert(tar);

    int d = 0;

    // Traverse level by level
    while (!q.empty() && d < k) {
        int sz = q.size();

        while (sz--) {
            Node* cur = q.front();
            q.pop();

            if (cur->left && !vis.count(cur->left)) {
                vis.insert(cur->left);
                q.push(cur->left);
            }

            if (cur->right && !vis.count(cur->right)) {
                vis.insert(cur->right);
                q.push(cur->right);
            }

            if (par.count(cur) && !vis.count(par[cur])) {
                vis.insert(par[cur]);
                q.push(par[cur]);
            }
        }

        d++;
    }

    while (!q.empty()) {
        ans.push_back(q.front()->data);
        q.pop();
    }

    // Sort the result
    sort(ans.begin(), ans.end());

    return ans;
}

int main() {

    // Create the binary tree:
    //       1
    //      / \
    //     2   3
    //    / \
    //   4   5

    Node* 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);

    int target = 2;
    int k = 2;

    vector<int> ans = kDistanceNodes(root, target, k);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Collections;

// Structure of Binary Tree Node
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {

    static HashMap<Node, Node> par = new HashMap<>();

    // Build the parent mapping and locate the target node
    static Node markParents(Node root, int target) {
        Node tar = null;

        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node cur = q.poll();

            if (cur.data == target)
                tar = cur;

            if (cur.left != null) {
                par.put(cur.left, cur);
                q.add(cur.left);
            }

            if (cur.right != null) {
                par.put(cur.right, cur);
                q.add(cur.right);
            }
        }

        return tar;
    }

    // Find nodes at distance k using BFS
    static ArrayList<Integer> kDistanceNodes(Node root, int target, int k) {
        ArrayList<Integer> ans = new ArrayList<>();

        // Build the parent mapping and find the target node
        Node tar = markParents(root, target);

        HashSet<Node> vis = new HashSet<>();
        Queue<Node> q = new LinkedList<>();

        q.add(tar);
        vis.add(tar);

        int d = 0;

        // Traverse level by level
        while (!q.isEmpty() && d < k) {
            int sz = q.size();

            while (sz-- > 0) {
                Node cur = q.poll();

                if (cur.left != null && !vis.contains(cur.left)) {
                    vis.add(cur.left);
                    q.add(cur.left);
                }

                if (cur.right != null && !vis.contains(cur.right)) {
                    vis.add(cur.right);
                    q.add(cur.right);
                }

                if (par.containsKey(cur) && !vis.contains(par.get(cur))) {
                    vis.add(par.get(cur));
                    q.add(par.get(cur));
                }
            }

            d++;
        }

        while (!q.isEmpty())
            ans.add(q.poll().data);

        // Sort the result
        Collections.sort(ans);

        return ans;
    }

    public static void main(String[] args) {

        // Create the binary tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5

        Node 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);

        int target = 2;
        int k = 2;

        ArrayList<Integer> ans = kDistanceNodes(root, target, k);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
from collections import deque

# Structure of Binary Tree Node
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# Build the parent mapping and locate the target node
def markParents(root, target, par):
    tar = None

    q = deque([root])

    while q:
        cur = q.popleft()

        if cur.data == target:
            tar = cur

        if cur.left:
            par[cur.left] = cur
            q.append(cur.left)

        if cur.right:
            par[cur.right] = cur
            q.append(cur.right)

    return tar


# Find nodes at distance k using BFS
def kDistanceNodes(root, target, k):
    ans = []

    if root is None:
        return ans

    par = {}

    # Build the parent mapping and find the target node
    tar = markParents(root, target, par)

    vis = set()
    q = deque([tar])

    vis.add(tar)

    d = 0

    # Traverse level by level
    while q and d < k:
        sz = len(q)

        while sz > 0:
            cur = q.popleft()

            if cur.left and cur.left not in vis:
                vis.add(cur.left)
                q.append(cur.left)

            if cur.right and cur.right not in vis:
                vis.add(cur.right)
                q.append(cur.right)

            if cur in par and par[cur] not in vis:
                vis.add(par[cur])
                q.append(par[cur])

            sz -= 1

        d += 1

    while q:
        ans.append(q.popleft().data)

    # Sort the result
    ans.sort()

    return ans


if __name__ == "__main__":

    # Create the binary tree:
    #       1
    #      / \
    #     2   3
    #    / \
    #   4   5

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    target = 2
    k = 2

    ans = kDistanceNodes(root, target, k)

    for x in ans:
        print(x, end=" ")
C#
using System;
using System.Collections.Generic;

// Structure of Binary Tree Node
class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {

    static Dictionary<Node, Node> par = new Dictionary<Node, Node>();

    // Build the parent mapping and locate the target node
    static Node markParents(Node root, int target) {
        Node tar = null;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node cur = q.Dequeue();

            if (cur.data == target)
                tar = cur;

            if (cur.left != null) {
                par[cur.left] = cur;
                q.Enqueue(cur.left);
            }

            if (cur.right != null) {
                par[cur.right] = cur;
                q.Enqueue(cur.right);
            }
        }

        return tar;
    }

    // Find nodes at distance k using BFS
    static List<int> kDistanceNodes(Node root, int target, int k) {
        List<int> ans = new List<int>();

        // Build the parent mapping and find the target node
        Node tar = markParents(root, target);

        HashSet<Node> vis = new HashSet<Node>();
        Queue<Node> q = new Queue<Node>();

        q.Enqueue(tar);
        vis.Add(tar);

        int d = 0;

        // Traverse level by level
        while (q.Count > 0 && d < k) {
            int sz = q.Count;

            while (sz-- > 0) {
                Node cur = q.Dequeue();

                if (cur.left != null && !vis.Contains(cur.left)) {
                    vis.Add(cur.left);
                    q.Enqueue(cur.left);
                }

                if (cur.right != null && !vis.Contains(cur.right)) {
                    vis.Add(cur.right);
                    q.Enqueue(cur.right);
                }

                if (par.ContainsKey(cur) &&
                    !vis.Contains(par[cur])) {
                    vis.Add(par[cur]);
                    q.Enqueue(par[cur]);
                }
            }

            d++;
        }

        while (q.Count > 0)
            ans.Add(q.Dequeue().data);

        // Sort the result
        ans.Sort();

        return ans;
    }

    public static void Main() {

        // Create the binary tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5

        Node 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);

        int target = 2;
        int k = 2;

        List<int> ans = kDistanceNodes(root, target, k);

        foreach (int x in ans)
            Console.Write(x + " ");
    }
}
JavaScript
// Structure of Binary Tree Node
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Build the parent mapping and locate the target node
function markParents(root, target, par)
{
    let tar = null;

    let q = [ root ];
    let front = 0;

    while (front < q.length) {
        let cur = q[front++];

        if (cur.data === target)
            tar = cur;

        if (cur.left) {
            par.set(cur.left, cur);
            q.push(cur.left);
        }

        if (cur.right) {
            par.set(cur.right, cur);
            q.push(cur.right);
        }
    }

    return tar;
}

// Find nodes at distance k using BFS
function kDistanceNodes(root, target, k)
{
    let ans = [];

    // Build the parent mapping and find the target node
    let par = new Map();
    let tar = markParents(root, target, par);

    let vis = new Set();
    let q = [ tar ];
    let front = 0;

    vis.add(tar);

    let d = 0;

    // Traverse level by level
    while (front < q.length && d < k) {
        let sz = q.length - front;

        while (sz--) {
            let cur = q[front++];

            if (cur.left && !vis.has(cur.left)) {
                vis.add(cur.left);
                q.push(cur.left);
            }

            if (cur.right && !vis.has(cur.right)) {
                vis.add(cur.right);
                q.push(cur.right);
            }

            if (par.has(cur) && !vis.has(par.get(cur))) {
                vis.add(par.get(cur));
                q.push(par.get(cur));
            }
        }

        d++;
    }

    while (front < q.length)
        ans.push(q[front++].data);

    // Sort the result
    ans.sort((a, b) => a - b);

    return ans;
}

// Driver code

// Create the binary tree:
//       1
//      / \
//     2   3
//    / \
//   4   5

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);

let target = 2;
let k = 2;

let ans = kDistanceNodes(root, target, k);

for (let x of ans)
    process.stdout.write(x + " ");

Output
3 
Comment