-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathFindLCAinBinaryTree.java
58 lines (38 loc) · 1.01 KB
/
FindLCAinBinaryTree.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
import java.util.ArrayList;
import java.util.List;
public class FindLCAinBinaryTree {
int findLCA(Node root, Node A, Node B) {
inorder(root);
postorder(root);
int positionA = inorderList.indexOf(A.value);
int positionB = inorderList.indexOf(B.value);
List<Integer> sublist = inorderList.subList(positionA, positionB);
int iNodeValue = 0;
for (Integer val : sublist) {
iNodeValue = Math.max(iNodeValue, postorderList.indexOf(val));
}
return iNodeValue;
}
List<Integer> inorderList = new ArrayList<Integer>();
List<Integer> postorderList = new ArrayList<Integer>();
public void inorder(Node n) {
if (n == null)
return;
inorder(n.left);
inorderList.add(n.value);
inorder(n.right);
}
public void postorder(Node n) {
if (n == null)
return;
postorder(n.left);
postorderList.add(n.value);
postorder(n.right);
}
}
/*
* Copyright 2004-2015 Pilz Ireland Industrial Automation Ltd. All Rights
* Reserved. PILZ PROPRIETARY/CONFIDENTIAL.
*
* Created on 12 May 2015
*/