-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0742-ClosestLeafInABinaryTree.cs
77 lines (69 loc) · 2.31 KB
/
0742-ClosestLeafInABinaryTree.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
//-----------------------------------------------------------------------------
// Runtime: 124ms
// Memory Usage: 30 MB
// Link: https://leetcode.com/submissions/detail/368912698/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class _0742_ClosestLeafInABinaryTree
{
public int FindClosestLeaf(TreeNode root, int k)
{
var graph = new Dictionary<TreeNode, IList<TreeNode>>();
BuildGraph(graph, null, root);
var queue = new Queue<TreeNode>();
var seen = new HashSet<TreeNode>();
foreach (var node in graph.Keys)
{
if (node.val == k)
{
queue.Enqueue(node);
seen.Add(node);
break;
}
}
while (queue.Count > 0)
{
var node = queue.Dequeue();
if (node == null) continue;
if (graph[node].Count <= 1) return node.val;
foreach (var next in graph[node])
{
if (!seen.Contains(next))
{
seen.Add(next);
queue.Enqueue(next);
}
}
}
return -1;
}
private void BuildGraph(Dictionary<TreeNode, IList<TreeNode>> graph, TreeNode parent, TreeNode node)
{
if (node == null) return;
if (parent != null)
{
if (!graph.ContainsKey(parent)) graph[parent] = new List<TreeNode>();
graph[parent].Add(node);
}
if (!graph.ContainsKey(node)) graph[node] = new List<TreeNode>();
graph[node].Add(parent);
BuildGraph(graph, node, node.left);
BuildGraph(graph, node, node.right);
}
}
}