-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-235.java
More file actions
30 lines (30 loc) · 856 Bytes
/
lc-235.java
File metadata and controls
30 lines (30 loc) · 856 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
else {
if(p.val < root.val && q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
}
if(p.val > root.val && q.val > root.val) {
return lowestCommonAncestor(root.right, p, q);
}
if(p.val <= root.val && q.val >= root.val) {
return root;
}
if(q.val >= root.val && q.val <= root.val) {
return root;
}else {
return root;
}
}
}
}