Skip to content

Commit 9ca291d

Browse files
edit 235
1 parent f10b4d2 commit 9ca291d

File tree

1 file changed

+14
-7
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+14
-7
lines changed

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

+14-7
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
import com.fishercoder.common.classes.TreeNode;
44

5-
/**Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
6-
7-
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
5+
/**
6+
* 235. Lowest Common Ancestor of a Binary Search Tree
7+
* Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
8+
* According to the definition of LCA on Wikipedia:
9+
* “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants
10+
* (where we allow a node to be a descendant of itself).”
811
912
_______6______
1013
/ \
@@ -13,15 +16,19 @@
1316
0 _4 7 9
1417
/ \
1518
3 5
16-
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
19+
20+
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6.
21+
Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
1722
1823
*/
1924
public class _235 {
25+
2026
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
2127
if (root == null || p == root || q == root) return root;
22-
if ((root.val - p.val) * (root.val - q.val) <= 0) return root;
23-
if ((root.val - p.val) * (root.val - q.val) > 0 && (root.val - p.val) > 0) return lowestCommonAncestor(root.left, p, q);
24-
if ((root.val - p.val) * (root.val - q.val) > 0 && (root.val - p.val) < 0) return lowestCommonAncestor(root.right, p, q);
28+
if ((root.val - p.val) * (root.val - q.val) > 0) {
29+
if (root.val - p.val > 0) return lowestCommonAncestor(root.left, p, q);
30+
return lowestCommonAncestor(root.right, p, q);
31+
}
2532
return root;
2633
}
2734
}

0 commit comments

Comments
 (0)