-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution863.cs
80 lines (65 loc) · 1.94 KB
/
Solution863.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution863
{
/// <summary>
/// 863. All Nodes Distance K in Binary Tree - Medium
/// <a href="https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree">See the problem</a>
/// </summary>
public IList<int> DistanceK(TreeNode root, TreeNode target, int k)
{
var graph = new Dictionary<int, List<int>>();
BuildGraph(root, null, graph);
var queue = new Queue<int>();
queue.Enqueue(target.val);
var visited = new HashSet<int> { target.val };
while (k > 0 && queue.Count > 0)
{
int size = queue.Count;
for (int i = 0; i < size; i++)
{
int node = queue.Dequeue();
if (graph.ContainsKey(node))
{
foreach (int neighbor in graph[node])
{
if (visited.Contains(neighbor))
{
continue;
}
visited.Add(neighbor);
queue.Enqueue(neighbor);
}
}
}
k--;
}
return [.. queue];
}
private void BuildGraph(TreeNode node, TreeNode parent, Dictionary<int, List<int>> graph)
{
if (node == null)
{
return;
}
if (!graph.ContainsKey(node.val))
{
graph[node.val] = new List<int>();
}
if (parent != null)
{
graph[node.val].Add(parent.val);
}
if (node.left != null)
{
graph[node.val].Add(node.left.val);
BuildGraph(node.left, node, graph);
}
if (node.right != null)
{
graph[node.val].Add(node.right.val);
BuildGraph(node.right, node, graph);
}
}
}