Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

All Nodes Distance K in Binary Tree LeetCode Solution

Problem – All Nodes Distance K in Binary Tree

Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.

You can return the answer in any order.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.

Example 2:

Input: root = [1], target = 1, k = 3
Output: []


  • The number of nodes in the tree is in the range [1, 500].
  • 0 <= Node.val <= 500
  • All the values Node.val are unique.
  • target is the value of one of the nodes in the tree.
  • 0 <= k <= 1000

All Nodes Distance K in Binary Tree LeetCode Solution in C++

class Solution {
    vector<int> ans;   
    map<TreeNode*, TreeNode*> parent;  // son=>parent  
    set<TreeNode*> visit;    //record visied node
    void findParent(TreeNode* node){
        if(!node ) return;
        if( node->left ){
            parent[node->left] = node;
        if( node->right){
            parent[node->right] = node;
    vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
        if( !root ) return {};
        dfs(target, K );
        return ans;
    void dfs( TreeNode* node, int K){
        if( visit.find(node) != visit.end() )
        if( K == 0 ){
        if( node->left ){
            dfs(node->left, K-1);
        if( node->right){
            dfs(node->right, K-1);
        TreeNode* p = parent[node];
        if( p )
            dfs(p, K-1);

All Nodes Distance K in Binary Tree LeetCode Solution in Python

def distanceK(self, root, target, K):
    conn = collections.defaultdict(list)
    def connect(parent, child):
        # both parent and child are not empty
        if parent and child:
            # building an undirected graph representation, assign the
            # child value for the parent as the key and vice versa
        # in-order traversal
        if child.left: connect(child, child.left)
        if child.right: connect(child, child.right)
    # the initial parent node of the root is None
    connect(None, root)
    # start the breadth-first search from the target, hence the starting level is 0
    bfs = [target.val]
    seen = set(bfs)
    # all nodes at (k-1)th level must also be K steps away from the target node
    for i in range(K):
        # expand the list comprehension to strip away the complexity
        new_level = []
        for q_node_val in bfs:
            for connected_node_val in conn[q_node_val]:
                if connected_node_val not in seen:
        bfs = new_level
        # add all the values in bfs into seen
        seen |= set(bfs)
    return bfs

All Nodes Distance K in Binary Tree LeetCode Solution in Java

class Solution {
    Map<TreeNode, Integer> map = new HashMap<>();
    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        List<Integer> res = new LinkedList<>();
        find(root, target);
        dfs(root, target, K, map.get(root), res);
        return res;
    // find target node first and store the distance in that path that we could use it later directly
    private int find(TreeNode root, TreeNode target) {
        if (root == null) return -1;
        if (root == target) {
            map.put(root, 0);
            return 0;
        int left = find(root.left, target);
        if (left >= 0) {
            map.put(root, left + 1);
            return left + 1;
		int right = find(root.right, target);
		if (right >= 0) {
            map.put(root, right + 1);
            return right + 1;
        return -1;
    private void dfs(TreeNode root, TreeNode target, int K, int length, List<Integer> res) {
        if (root == null) return;
        if (map.containsKey(root)) length = map.get(root);
        if (length == K) res.add(root.val);
        dfs(root.left, target, K, length + 1, res);
        dfs(root.right, target, K, length + 1, res);
All Nodes Distance K in Binary Tree LeetCode Solution Review:

In our experience, we suggest you solve this All Nodes Distance K in Binary Tree LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the All Nodes Distance K in Binary Tree LeetCode Solution

Find on LeetCode


I hope this All Nodes Distance K in Binary Tree LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *