@@ -22,23 +22,27 @@ For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3.
22
22
Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.*/
23
23
24
24
public class _236 {
25
-
26
- /**We need to find TWO nodes in the tree,
27
- * so we'll have to divide and conquer this tree,
28
- * we need to have two nodes to as the intermediate result,
29
- * also, refer to my earlier drawings:http://www.fishercoder.com/2016/06/23/lowest-common-ancestor-of-a-binary-tree/
30
- * I'm really impressed with myself at that time!*/
31
-
32
- public TreeNode lowestCommonAncestor (TreeNode root ,TreeNode p ,TreeNode q ) {
33
- if (root ==null ||root ==p ||root ==q ) {
34
- return root ;
35
- }
36
- TreeNode left =lowestCommonAncestor (root .left ,p ,q );
37
- TreeNode right =lowestCommonAncestor (root .right ,p ,q );
38
- if (left !=null &&right !=null ) {
39
- return root ;
25
+ public static class Solution1 {
26
+
27
+ /**
28
+ * We need to find TWO nodes in the tree,
29
+ * so we'll have to divide and conquer this tree,
30
+ * we need to have two nodes to as the intermediate result,
31
+ * also, refer to my earlier drawings:http://www.fishercoder.com/2016/06/23/lowest-common-ancestor-of-a-binary-tree/
32
+ * I'm really impressed with myself at that time!
33
+ */
34
+
35
+ public TreeNode lowestCommonAncestor (TreeNode root ,TreeNode p ,TreeNode q ) {
36
+ if (root ==null ||root ==p ||root ==q ) {
37
+ return root ;
38
+ }
39
+ TreeNode left =lowestCommonAncestor (root .left ,p ,q );
40
+ TreeNode right =lowestCommonAncestor (root .right ,p ,q );
41
+ if (left !=null &&right !=null ) {
42
+ return root ;
43
+ }
44
+ return left !=null ?left :right ;
40
45
}
41
- return left !=null ?left :right ;
42
46
}
43
47
44
48
}