Skip to content

Commit 104c54a

Browse files
refactor 236
1 parent a08a9fd commit 104c54a

File tree

1 file changed

+20
-16
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+20
-16
lines changed

src/main/java/com/fishercoder/solutions/_236.java

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,27 @@ For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3.
2222
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.*/
2323

2424
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;
4045
}
41-
return left != null ? left : right;
4246
}
4347

4448
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy