-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
53 lines (50 loc) · 1.48 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
using System;
using System.Collections.Generic;
namespace LowestCommonAncestorOfABinaryTreeII
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
static TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
var pAncestor = new List<TreeNode>();
var qAncestor = new List<TreeNode>();
var found = false;
DFS(root, p, pAncestor, ref found);
found = false;
DFS(root, q, qAncestor, ref found);
var set = new HashSet<TreeNode>();
foreach (var node in pAncestor)
set.Add(node);
foreach (var node in qAncestor)
{
if (set.Contains(node))
return node;
}
return null;
}
static void DFS(TreeNode node, TreeNode target, List<TreeNode> ancestor, ref bool found)
{
if (node == null || found) return;
if(node == target)
{
found = true;
ancestor.Add(node);
}
DFS(node.left, target, ancestor, ref found);
DFS(node.right, target, ancestor, ref found);
if (found)
ancestor.Add(node);
}
}
}