File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ import DS .TreeNode ;
2
+
3
+ /*
4
+ // Definition of TreeNode:
5
+ class TreeNode {
6
+ public int val;
7
+ public TreeNode left;
8
+ public TreeNode right;
9
+ public TreeNode(int val) {
10
+ this.val = val;
11
+ }
12
+ }
13
+ */
14
+
15
+ public class LowestCommonAncestor {
16
+ TreeNode lca ;
17
+
18
+ public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
19
+ dfs (root , p , q );
20
+ return lca ;
21
+ }
22
+
23
+ private boolean dfs (TreeNode node , TreeNode p , TreeNode q ) {
24
+ // Base case: a null node is neither 'p' nor 'q'.
25
+ if (node == null ) {
26
+ return false ;
27
+ }
28
+ int nodeIsPOrQ = (node == p || node == q ) ? 1 : 0 ;
29
+ // Recursively determine if the left and right subtrees contain 'p'
30
+ // or 'q'.
31
+ int leftContainsPOrQ = dfs (node .left , p , q ) ? 1 : 0 ;
32
+ int rightContainsPOrQ = dfs (node .right , p , q ) ? 1 : 0 ;
33
+ // If two of the above three variables are true, the current node is
34
+ // the LCA.
35
+ if (nodeIsPOrQ + leftContainsPOrQ + rightContainsPOrQ == 2 ) {
36
+ lca = node ;
37
+ }
38
+ // Return true if the current subtree contains 'p' or 'q'.
39
+ return nodeIsPOrQ + leftContainsPOrQ + rightContainsPOrQ > 0 ;
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments