All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : July 04, 2024
Last updated : July 04, 2024
Related Topics : Tree, Depth-First Search, Binary Search Tree, Binary Tree
Acceptance Rate : 67.82 %
# 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 :
if (root == p) or (root == q) :
break
if (root.val < p.val) == (root.val > q.val) :
break
if root.val < p.val :
root = root.right
else :
root = root.left
return root