-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
67 lines (63 loc) · 1.56 KB
/
Program.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
using System;
using System.Collections.Generic;
namespace FindRootOfNAryTree
{
public class Node
{
public int val;
public IList<Node> children;
public Node()
{
val = 0;
children = new List<Node>();
}
public Node(int _val)
{
val = _val;
children = new List<Node>();
}
public Node(int _val, List<Node> _children)
{
val = _val;
children = _children;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
public Node FindRoot_HashSet(List<Node> tree)
{
var set = new HashSet<Node>();
foreach (var node in tree)
{
foreach (var child in node.children)
set.Add(child);
}
foreach (var node in tree)
{
if (!set.Contains(node))
return node;
}
return null;
}
public Node FindRoot_O1Space(List<Node> tree)
{
int sum = 0, childernSum = 0;
foreach (var node in tree)
{
sum += node.val;
foreach (var child in node.children)
childernSum += child.val;
}
foreach (var node in tree)
{
if (node.val == sum - childernSum)
return node;
}
return null;
}
}
}