-
Notifications
You must be signed in to change notification settings - Fork 1
/
LCABT2.java
48 lines (39 loc) · 1.23 KB
/
LCABT2.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
package trees.binary;
import annotation.Platform;
import annotation.Quality;
import annotation.Site;
import annotation.Stage;
import model.TreeNode;
/**
* @author g1patil
* 1644. Lowest Common Ancestor of a Binary Tree II
*
* Diff with 235/236 : is that either node can be missing from the tree
* For that we need to traverse first and then do the computation
*/
@Quality(Stage.TESTED)
@Platform(Site.LEETCODE)
public class LCABT2 {
int foundCount = 0;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode lca = lowestCommonAncestorHelper(root , p , q );
return foundCount == 2 ? lca : null;
}
public TreeNode lowestCommonAncestorHelper(TreeNode root, TreeNode p, TreeNode q){
if(root == null)
return root;
/* traverse first */
TreeNode left = lowestCommonAncestorHelper(root.left , p , q);
TreeNode right = lowestCommonAncestorHelper(root.right , p , q );
/* compute the answer */
if(root == p){
foundCount++;
return root;
}
if(root == q){
foundCount++;
return root;
}
return left == null ? right : right == null ? left : root;
}
}