-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ235LowestCommonAncestor.py
More file actions
28 lines (19 loc) · 936 Bytes
/
Q235LowestCommonAncestor.py
File metadata and controls
28 lines (19 loc) · 936 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
27
28
# @b-knd (jingru) on 11 August 2022 10:08:00
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
while root != p and root != q:
if p.val < root.val and q.val > root.val or p.val > root.val and q.val < root.val:
return root
if p.val < root.val and q.val < root.val:
root = root.left
else:
root = root.right
return root
#Runtime: 95 ms, faster than 78.79% of Python3 online submissions for Lowest Common Ancestor of a Binary Search Tree.
#Memory Usage: 18.9 MB, less than 22.99% of Python3 online submissions for Lowest Common Ancestor of a Binary Search Tree.