-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path235.java
51 lines (50 loc) · 1.6 KB
/
235.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
__________________________________________________________________________________________________
sample 4 ms submission
/**
* 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.val > Math.max(p.val, q.val)) {
return lowestCommonAncestor(root.left, p, q);
} else if (root.val < Math.min(p.val, q.val)) {
return lowestCommonAncestor(root.right, p, q);
} else {
return root;
}
}
}
__________________________________________________________________________________________________
sample 32644 kb submission
/**
* 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(p.val < q.val) {
return findLCA(root, p, q);
}
else {
return findLCA(root, q, p);
}
}
public TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {
if(root.val > p.val && root.val < q.val) return root;
if(root == p || root == q) return root;
if(root.val > q.val) return findLCA(root.left, p, q);
else return findLCA(root.right, p, q);
}
}
__________________________________________________________________________________________________