|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
4 | 4 |
|
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).” |
8 | 11 |
|
9 | 12 | _______6______
|
10 | 13 | / \
|
|
13 | 16 | 0 _4 7 9
|
14 | 17 | / \
|
15 | 18 | 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. |
17 | 22 |
|
18 | 23 | */
|
19 | 24 | public class _235 {
|
| 25 | + |
20 | 26 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
21 | 27 | 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 | + } |
25 | 32 | return root;
|
26 | 33 | }
|
27 | 34 | }
|
0 commit comments