{"id":22514008,"url":"https://github.com/emahtab/all-nodes-distance-k-in-binary-tree","last_synced_at":"2026-03-19T23:03:10.754Z","repository":{"id":79525230,"uuid":"412804015","full_name":"eMahtab/all-nodes-distance-k-in-binary-tree","owner":"eMahtab","description":"All nodes distance k in a binary tree","archived":false,"fork":false,"pushed_at":"2021-10-02T15:29:26.000Z","size":711,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-02T03:26:22.280Z","etag":null,"topics":["breadth-first-search","graph","leetcode"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-10-02T13:27:11.000Z","updated_at":"2022-01-30T04:18:21.000Z","dependencies_parsed_at":"2023-05-10T17:00:26.975Z","dependency_job_id":null,"html_url":"https://github.com/eMahtab/all-nodes-distance-k-in-binary-tree","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fall-nodes-distance-k-in-binary-tree","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fall-nodes-distance-k-in-binary-tree/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fall-nodes-distance-k-in-binary-tree/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fall-nodes-distance-k-in-binary-tree/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/all-nodes-distance-k-in-binary-tree/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245952488,"owners_count":20699492,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["breadth-first-search","graph","leetcode"],"created_at":"2024-12-07T03:15:34.271Z","updated_at":"2026-01-07T07:17:58.763Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# All nodes distance k in binary tree\nAll nodes distance k in a binary tree\n\n## https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree\n\nGiven 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.\n\n**You can return the answer in any order.**\n\n![All nodes distance k in binary tree](all-nodes-distance-k-in-binary-tree.jpg?raw=true)\n\n## Approach : Create graph from the given tree and BFS\nWe will first create a graph from the given binary tree.\nOnce we have the graph, all we need to do is, to find all the nodes which have distance k from the targetNode using BFS (start BFS from targetNode).\n\n# Implementation :\n```java\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n    TreeNode sourceNode;\n    public List\u003cInteger\u003e distanceK(TreeNode root, TreeNode target, int k) {\n        List\u003cInteger\u003e result = new ArrayList\u003c\u003e();\n        if(root == null)\n            return result;\n        Map\u003cInteger,List\u003cTreeNode\u003e\u003e graph = new HashMap\u003c\u003e();\n        // Create a graph representation from given binary tree\n        dfs(root, graph, null, target);\n        // Next do BFS traversal to find all the nodes distance k from target node\n        Queue\u003cTreeNode\u003e q = new ArrayDeque\u003c\u003e();\n        Set\u003cInteger\u003e visited = new HashSet\u003c\u003e();\n        // Start the BFS from given target node\n        q.add(sourceNode);\n        visited.add(sourceNode.val);\n        int distance = 0;\n        while(!q.isEmpty() \u0026\u0026 distance \u003c= k) {\n            int size = q.size();\n            for(int i = 0; i \u003c size; i++) {\n                TreeNode node = q.remove();\n                if(distance == k)\n                    result.add(node.val);\n                List\u003cTreeNode\u003e neighbors = graph.get(node.val);\n                // add neighbors to the queue\n                for(TreeNode neighbor : neighbors) {\n                    if(!visited.contains(neighbor.val)) {\n                        q.add(neighbor);\n                        visited.add(neighbor.val);\n                    }  \n                }\n            }\n            distance++;\n        }\n        return result;\n    }\n    \n    private void dfs(TreeNode node, Map\u003cInteger, List\u003cTreeNode\u003e\u003e graph, TreeNode parent, TreeNode target) {\n        if(node == null)\n            return;\n        if(node.val == target.val)\n            sourceNode = node;\n        graph.putIfAbsent(node.val, new ArrayList\u003cTreeNode\u003e());\n        List\u003cTreeNode\u003e neighbors = graph.get(node.val);\n        if(node.left != null)\n            neighbors.add(node.left);\n        if(node.right != null)\n            neighbors.add(node.right);\n        if(parent != null) {\n            neighbors.add(parent);\n        }\n        dfs(node.left, graph, node, target);\n        dfs(node.right, graph, node, target);\n    }\n}\n```\n\n## Complexity Analysis :\n```\nTime Complexity: O(N) where N is the number of nodes in the given input tree.\n\nSpace Complexity: O(N), the size of the graph.\n```\n\n# References :\nhttps://github.com/eMahtab/closest-leaf-in-a-binary-tree\n\n# Similar Question :\nClosest leaf in a binary tree https://leetcode.com/problems/closest-leaf-in-a-binary-tree\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fall-nodes-distance-k-in-binary-tree","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fall-nodes-distance-k-in-binary-tree","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fall-nodes-distance-k-in-binary-tree/lists"}