|
40 | 40 | # Final Solution *
|
41 | 41 | # ****************
|
42 | 42 | class Solution(object):
|
| 43 | + #Iterative |
43 | 44 | def lowestCommonAncestor(self, root, p, q):
|
44 | 45 | if not root or not p or not q:
|
45 | 46 | return None
|
46 | | - if max(p.val, q.val) < root.val: |
| 47 | + |
| 48 | + while root: |
| 49 | + if root.val > max(p.val, q.val): |
| 50 | + root = root.left |
| 51 | + elif root.val < min(p.val, q.val): |
| 52 | + root = root.right |
| 53 | + else: |
| 54 | + return root |
| 55 | + |
| 56 | + |
| 57 | + #Recursion |
| 58 | + def lowestCommonAncestor2(self, root, p, q): |
| 59 | + if not root or not p or not q: |
| 60 | + return None |
| 61 | + if root.val > max(p.val, q.val): |
47 | 62 | return self.lowestCommonAncestor(root.left, p, q)
|
48 | | - elif min(p.val, q.val) > root.val: |
49 | | - return self.lowestCommonAncestor(root.right, p ,q) |
50 | | - return root |
| 63 | + elif root.val < min(p.val, q.val): |
| 64 | + return self.lowestCommonAncestor(root.right, p, q) |
| 65 | + else: |
| 66 | + return root |
0 commit comments