|
| 1 | +/** |
| 2 | + * 863. All Nodes Distance K in Binary Tree |
| 3 | + * https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, the value of a target node target, and an integer k, return an |
| 7 | + * array of the values of all nodes that have a distance k from the target node. |
| 8 | + * |
| 9 | + * You can return the answer in any order. |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Definition for a binary tree node. |
| 14 | + * function TreeNode(val) { |
| 15 | + * this.val = val; |
| 16 | + * this.left = this.right = null; |
| 17 | + * } |
| 18 | + */ |
| 19 | +/** |
| 20 | + * @param {TreeNode} root |
| 21 | + * @param {TreeNode} target |
| 22 | + * @param {number} k |
| 23 | + * @return {number[]} |
| 24 | + */ |
| 25 | +var distanceK = function(root, target, k) { |
| 26 | + const graph = new Map(); |
| 27 | + const result = []; |
| 28 | + |
| 29 | + buildGraph(root, null); |
| 30 | + findNodesAtDistance(target.val, 0, new Set()); |
| 31 | + |
| 32 | + return result; |
| 33 | + |
| 34 | + function buildGraph(node, parent) { |
| 35 | + if (!node) return; |
| 36 | + if (parent) { |
| 37 | + graph.set(node.val, graph.get(node.val) || new Set()); |
| 38 | + graph.get(node.val).add(parent.val); |
| 39 | + graph.set(parent.val, graph.get(parent.val) || new Set()); |
| 40 | + graph.get(parent.val).add(node.val); |
| 41 | + } |
| 42 | + buildGraph(node.left, node); |
| 43 | + buildGraph(node.right, node); |
| 44 | + } |
| 45 | + |
| 46 | + function findNodesAtDistance(currentVal, distance, visited) { |
| 47 | + if (distance === k) { |
| 48 | + result.push(currentVal); |
| 49 | + return; |
| 50 | + } |
| 51 | + visited.add(currentVal); |
| 52 | + const neighbors = graph.get(currentVal) || new Set(); |
| 53 | + for (const neighbor of neighbors) { |
| 54 | + if (!visited.has(neighbor)) { |
| 55 | + findNodesAtDistance(neighbor, distance + 1, visited); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +}; |
0 commit comments