-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain68.java
More file actions
26 lines (24 loc) · 782 Bytes
/
Main68.java
File metadata and controls
26 lines (24 loc) · 782 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
package JZOffer2;
public class Main68 {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root!=null){
if(root.val < p.val && root.val < q.val){
root = root.right;
}
else if(root.val > p.val && root.val > q.val){
root = root.left;
}
else{
break;
}
}
return root;
}
public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
if(root.val < p.val && root.val < q.val)
return lowestCommonAncestor1(root.right, p, q);
if(root.val > p.val && root.val > q.val)
return lowestCommonAncestor1(root.left, p, q);
return root;
}
}