Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7998521

Browse files
author
Yu Zhou
committed
quick update 235
1 parent 9f1d69d commit 7998521

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

‎tree/Yu/235_lca_bst.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,27 @@
4040
# Final Solution *
4141
# ****************
4242
class Solution(object):
43+
#Iterative
4344
def lowestCommonAncestor(self, root, p, q):
4445
if not root or not p or not q:
4546
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):
4762
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /