-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCA.java
67 lines (55 loc) · 1.62 KB
/
LCA.java
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
/*
Find the lowest common ancestor in an unordered binary tree given two values in the tree.
Lowest common ancestor : the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) is the lowest (i.e. deepest) node that has both v and w as descendants.
Example :
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2_ 0 8
/ \
7 4
*/
public int lca(TreeNode a, int b, int c) {
if(a==null)
return -1;
if(a.right==null && a.left==null)
return -1;
ArrayList<Integer> nodeB = new ArrayList<Integer>();
ArrayList<Integer> nodeC = new ArrayList<Integer>();
boolean cFlag= findNode(a, c, nodeC);
boolean bFlag = findNode(a, b, nodeB);
if(!cFlag || !bFlag )
return -1;
for( int i =0; i<nodeB.size();i++ )
{
for( int j =0; i<nodeC.size(); j++)
{
if(nodeB.get(i)== nodeC.get(j))
return nodeB.get(i);
}
}
return -1;
}
boolean findNode(TreeNode a, int b, ArrayList<Integer> path)
{
if(a==null)
return false;
if(a.val==b) {
path.add(a.val);
return true;
}
boolean left = findNode(a.left,b, path);
boolean right = findNode(a.right, b,path);
if(left)
{
path.add(a.val);
return true;
}
else if(right)
{
path.add(aval);
return true;
}
return false;
}