Let p be smaller than q.
If root > q, p and q's lowest common ancestor is in the left sub-tree.
If root < p, p and q's lowest common ancestor is in the right sub-tree.
Otherwise, we find the lowest common ancestor of p and q.
Time complexity = O ( N )
# 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':
if not root:
return root
# make sure p < q
if p.val > q.val:
p, q = q, p
if root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
if root.val < p.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
No comments:
Post a Comment