{"id":22513950,"url":"https://github.com/emahtab/closest-leaf-in-a-binary-tree","last_synced_at":"2026-03-19T23:03:19.801Z","repository":{"id":79525357,"uuid":"412706775","full_name":"eMahtab/closest-leaf-in-a-binary-tree","owner":"eMahtab","description":"Closest Leaf node from a given node in a binary tree","archived":false,"fork":false,"pushed_at":"2022-08-31T05:13:39.000Z","size":1445,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-02T03:26:11.961Z","etag":null,"topics":["breadth-first-search","closest-leaf","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-02T06:06:51.000Z","updated_at":"2021-10-02T13:40:18.000Z","dependencies_parsed_at":"2023-05-10T17:15:44.985Z","dependency_job_id":null,"html_url":"https://github.com/eMahtab/closest-leaf-in-a-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%2Fclosest-leaf-in-a-binary-tree","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fclosest-leaf-in-a-binary-tree/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fclosest-leaf-in-a-binary-tree/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fclosest-leaf-in-a-binary-tree/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/closest-leaf-in-a-binary-tree/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245952293,"owners_count":20699464,"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","closest-leaf","graph","leetcode"],"created_at":"2024-12-07T03:15:14.068Z","updated_at":"2026-01-06T18:09:38.387Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Closest Leaf in a binary tree\nClosest Leaf node from a given node in a binary tree\n\n## https://leetcode.com/problems/closest-leaf-in-a-binary-tree\n## https://www.lintcode.com/problem/854\n\nGiven the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree.\n\nNearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.\n\n```\nConstraints:\n\n1. The number of nodes in the tree is in the range [1, 1000].\n2. 1 \u003c= Node.val \u003c= 1000\n3. All the values of the tree are unique.\n4. There exist some node in the tree where Node.val == k.\n\n```\n\n\n## Approach : Create graph from the given tree and BFS\nWe will first create a graph from the given binary tree. Once we have the graph, all we need to do is, to find the first leaf node using BFS, starting from the sourceNode `k`.\nSo this problem is, finding the shortest path in an unweighted undirected graph. \n\n![\"Closest leaf in a binary tree\"](closest-leaf-in-a-binary-tree.jpg?raw=true)\n\n# Implementation : Graph + BFS\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() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    TreeNode sourceNode = null;\n    public int findClosestLeaf(TreeNode root, int k) {\n        if(root == null)\n            return -1;\n        Map\u003cInteger,List\u003cTreeNode\u003e\u003e graph = new HashMap\u003c\u003e();\n        // Create a graph representation from given binary \n        dfs(root, graph, null, k);\n        // Next do BFS traversal to find the closest leaf to node k\n        Queue\u003cTreeNode\u003e q = new ArrayDeque\u003c\u003e();\n        Set\u003cInteger\u003e visited = new HashSet\u003c\u003e();\n        // Start the BFS from the sourceNode k\n        q.add(sourceNode);\n        visited.add(sourceNode.val);\n        while(!q.isEmpty()) {\n            \n                TreeNode node = q.remove();\n                if(node.left == null \u0026\u0026 node.right == null)\n                    return 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        }\n        return -1;\n    }\n    \n    private void dfs(TreeNode node, Map\u003cInteger, List\u003cTreeNode\u003e\u003e graph, TreeNode parent, int k) {\n        if(node == null)\n            return;\n        if(node.val == k)\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, k);\n        dfs(node.right, graph, node, k);\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\n# References :\n1. https://leetcode.com/problems/closest-leaf-in-a-binary-tree/solution\n\n## Similar Question :\nAll nodes distance k in a binary tree https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fclosest-leaf-in-a-binary-tree","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fclosest-leaf-in-a-binary-tree","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fclosest-leaf-in-a-binary-tree/lists"}