-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Lowest Common Ancestor of a Binary Search Tree
- Loading branch information
1 parent
21793ef
commit 0031a85
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
python/leetcode/Lowest Common Ancestor of a Binary Search Tree.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
from python.leetcode.libs.tree import TreeNode | ||
|
||
|
||
class Solution: | ||
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': | ||
|
||
min_node, max_node = (p, q) if p.val < q.val else (q, p) | ||
|
||
answer = None | ||
|
||
def traceback(node): | ||
nonlocal answer | ||
if not node: | ||
return | ||
|
||
if node.val >= min_node.val and node.val <= max_node.val: | ||
answer = node | ||
return | ||
|
||
if node.val < min_node.val and node.val < max_node.val: | ||
traceback(node.right) | ||
else: | ||
traceback(node.left) | ||
|
||
traceback(root) | ||
|
||
return answer | ||
|
||
|
||
if __name__ == "__main__": | ||
obj = Solution() | ||
|
||
root = TreeNode.array_to_tree([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5]) | ||
p = 2 | ||
q = 4 | ||
assert obj.lowestCommonAncestor(root, root.left, root.left.right).val == root.left.val | ||
|
||
root = TreeNode.array_to_tree([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5]) | ||
assert obj.lowestCommonAncestor(root, root.left, root.right).val == root.val |