Skip to content

Commit e4e589d

Browse files
authored
Update Lowest Common Ancestor of a Binary Search Tree.java
1 parent 0b179f2 commit e4e589d

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

Easy/Lowest Common Ancestor of a Binary Search Tree.java

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,16 @@
77
* TreeNode(int x) { val = x; }
88
* }
99
*/
10+
1011
class Solution {
1112
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12-
if (root == null || p == null || q == null) {
13-
return null;
14-
}
15-
if (root == p || root == q) {
16-
return root;
17-
}
18-
if ((root.val > p.val && root.val < q.val) || (root.val < p.val && root.val > q.val)) {
13+
if (root == p || root == q ||
14+
(p.val > root.val && q.val < root.val) ||
15+
(p.val < root.val && q.val > root.val)) {
1916
return root;
2017
}
21-
if (root.val > p.val && root.val > q.val) {
22-
return lowestCommonAncestor(root.left, p, q);
23-
}
24-
else {
25-
return lowestCommonAncestor(root.right, p, q);
26-
}
18+
return ((root.val > p.val && root.val > q.val) ?
19+
lowestCommonAncestor(root.left, p, q) :
20+
lowestCommonAncestor(root.right, p, q));
2721
}
2822
}

0 commit comments

Comments
 (0)