-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0863-AllNodesDistanceKInBinaryTree.cs
74 lines (66 loc) · 2.41 KB
/
0863-AllNodesDistanceKInBinaryTree.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
//-----------------------------------------------------------------------------
// Runtime: 240ms
// Memory Usage: 31.9 MB
// Link: https://leetcode.com/submissions/detail/366243160/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class _0863_AllNodesDistanceKInBinaryTree
{
public IList<int> DistanceK(TreeNode root, TreeNode target, int K)
{
var connections = new Dictionary<TreeNode, IList<TreeNode>>();
BuildGraph(null, root, connections);
var seen = new HashSet<TreeNode>();
var queue = new Queue<TreeNode>();
seen.Add(target);
queue.Enqueue(target);
while (queue.Count > 0 && K > 0)
{
var size = queue.Count;
for (int i = 0; i < size; i++)
{
var node = queue.Dequeue();
if (!connections.ContainsKey(node)) continue;
foreach (var neighbor in connections[node])
{
if (!seen.Contains(neighbor))
{
seen.Add(neighbor);
queue.Enqueue(neighbor);
}
}
}
K--;
}
return queue.Select(node => node.val).ToList();
}
private void BuildGraph(TreeNode parent, TreeNode child, Dictionary<TreeNode, IList<TreeNode>> connection)
{
if (parent != null && child != null)
{
if (!connection.ContainsKey(parent))
connection[parent] = new List<TreeNode>();
if (!connection.ContainsKey(child))
connection[child] = new List<TreeNode>();
connection[parent].Add(child);
connection[child].Add(parent);
}
if (child.left != null)
BuildGraph(child, child.left, connection);
if (child.right != null)
BuildGraph(child, child.right, connection);
}
}
}