1+ package com .rampatra .trees ;
2+
3+ /**
4+ * Given a binary tree {@code root}, find the LCA of two given nodes {@code node1} and {@code node2}. LCA is a node
5+ * which is closest to both of the nodes.
6+ * <p>
7+ * See this <a href="https://www.youtube.com/watch?v=O4zB91sMKhM">youtube video</a> for a visual understanding of the
8+ * approach taken to solve this problem.
9+ *
10+ * @author rampatra
11+ * @since 2019-04-06
12+ */
13+ public class LeastCommonAncestorInBT {
14+ private static class TreeNode {
15+ int val ;
16+ TreeNode left ;
17+ TreeNode right ;
18+
19+ TreeNode (int val ) {
20+ this .val = val ;
21+ }
22+
23+ @ Override
24+ public String toString () {
25+ return String .valueOf (val );
26+ }
27+ }
28+
29+ private static TreeNode findLCA (TreeNode root , TreeNode node1 , TreeNode node2 ) {
30+ if (root == null ) return null ;
31+
32+ TreeNode left = findLCA (root .left , node1 , node2 );
33+ TreeNode right = findLCA (root .right , node1 , node2 );
34+
35+ if (root == node1 || root == node2 ) {
36+ return root ;
37+ } else if (left != null && right != null ) { // one node is in the left sub-tree and the other on the right sub-tree
38+ return root ;
39+ } else if (left != null ) { // we found one node in the left sub-tree
40+ return left ;
41+ } else if (right != null ) { // we found one node in the right sub-tree
42+ return right ;
43+ } else {
44+ return null ;
45+ }
46+ }
47+
48+ public static void main (String [] args ) {
49+ /*
50+ The BST looks like:
51+
52+ 4
53+ / \
54+ 2 8
55+ / \ / \
56+ 1 3 6 9
57+ /
58+ 0
59+
60+ */
61+ TreeNode treeRoot = new TreeNode (4 );
62+ treeRoot .left = new TreeNode (2 );
63+ treeRoot .right = new TreeNode (8 );
64+ treeRoot .left .left = new TreeNode (1 );
65+ treeRoot .left .right = new TreeNode (3 );
66+ treeRoot .left .left .left = new TreeNode (0 );
67+ treeRoot .right .left = new TreeNode (6 );
68+ treeRoot .right .right = new TreeNode (9 );
69+
70+ System .out .println (findLCA (treeRoot , treeRoot , treeRoot ).val ); // findLCA(4, 4)
71+ System .out .println (findLCA (treeRoot , treeRoot .left , treeRoot .right ).val ); // findLCA(2, 8)
72+ System .out .println (findLCA (treeRoot , treeRoot .left , treeRoot .left .left ).val ); // findLCA(2, 1)
73+ System .out .println (findLCA (treeRoot , treeRoot .left .left , treeRoot .left ).val ); // findLCA(1, 2)
74+ System .out .println (findLCA (treeRoot , treeRoot .left .left .left , treeRoot .right .left ).val ); // findLCA(0, 6)
75+ System .out .println (findLCA (treeRoot , treeRoot .right , treeRoot .right .right ).val ); // findLCA(8, 9)
76+ }
77+ }
0 commit comments