Skip to content

Instantly share code, notes, and snippets.

@DrynnBavis
Created December 6, 2018 06:43
Show Gist options
  • Select an option

  • Save DrynnBavis/27c9dbd72a38e0fc1b5993577a1a081b to your computer and use it in GitHub Desktop.

Select an option

Save DrynnBavis/27c9dbd72a38e0fc1b5993577a1a081b to your computer and use it in GitHub Desktop.
Returns the lowest common ancestor in a BST
# 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, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
# check left side
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
# check right side
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
# both p and q aren't on one side -> root is result
return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment