-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path235. Lowest Common Ancestor of a Binary Search Tree
56 lines (51 loc) · 1.75 KB
/
235. Lowest Common Ancestor of a Binary Search Tree
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
52
53
54
55
56
/*
*/
This is the code for the second time;
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p==null)
return q;
if(q==null)
return p;
if(p==root|q==root)
return root;
if((p.val>root.val&q.val<root.val)|(q.val>root.val&p.val<root.val))
return root;
if(p.val>root.val&q.val>root.val)
return lowestCommonAncestor(root.right,p,q);
else
return lowestCommonAncestor(root.left,p,q);
}
}
This is the first time
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null)
return null;
if(p==null)
return q;
if(q==null)
return p;
if(root.val==p.val|root.val==q.val) // I forget this condition in the beginning, in the end if the root is 2, root.left
//is 2,then q=1; basically the return would be null rather than 2
return root;
if(root.left==null)
{root=root.right;
return lowestCommonAncestor(root,p,q);
}
else if(root.right==null)
{
return lowestCommonAncestor(root.left,p,q);
}
else
{ int a=Math.max(p.val,q.val);
int b=Math.min(p.val,q.val);
if(b<root.val&&a<root.val) //Be careful that do not lose .val, another thing is that compared to root, rather than root.left or root.right
return lowestCommonAncestor(root.left,p,q);
else if(b<root.val&&a>root.val)
return root;
else
return lowestCommonAncestor(root.right,p,q);
}
}
}