File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given a binary tree (not a binary search tree) and two values say n1 and n2,
3
+ * write a program to find the least common ancestor.
4
+ * Allow a node to be a descendant of itself
5
+ *
6
+ * Tags: Tree
7
+ */
8
+ class LowestCommonAncestor {
9
+ public static void main (String [] args ) {
10
+
11
+ }
12
+
13
+ /**
14
+ * If root is null, just return null
15
+ * If root's value matches with n1 or n2, return root
16
+ * If not, find lca recursively in both left and right subtrees
17
+ * If both are not null, one value in left and the other in right,
18
+ * return root
19
+ * If one is not null, return that one
20
+ */
21
+ public Node findLca (Node root , int n1 , int n2 ) {
22
+ if (root == null ) return null ;
23
+ if (root .val == n1 || root .val == n2 ) return root ;
24
+
25
+ Node leftLca = findLca (root .left , n1 , n2 );
26
+ Node rightLca = findLca (root .right , n1 , n2 );
27
+ if (leftLca != null && rightLca != null ) return root ;
28
+ return leftLca != null ? leftLca : rightLca ;
29
+ }
30
+
31
+ class Node {
32
+ int val ;
33
+ Node left ;
34
+ Node right ;
35
+
36
+ public Node () {}
37
+
38
+ public Node (int v ) {
39
+ val = v ;
40
+ }
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments