Skip to content

Commit fc9d313

Browse files
committed
Add solution #863
1 parent 58fdd0c commit fc9d313

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,7 @@
670670
860|[Lemonade Change](./0860-lemonade-change.js)|Easy|
671671
861|[Score After Flipping Matrix](./0861-score-after-flipping-matrix.js)|Medium|
672672
862|[Shortest Subarray with Sum at Least K](./0862-shortest-subarray-with-sum-at-least-k.js)|Hard|
673+
863|[All Nodes Distance K in Binary Tree](./0863-all-nodes-distance-k-in-binary-tree.js)|Medium|
673674
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
674675
868|[Binary Gap](./0868-binary-gap.js)|Easy|
675676
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)