Created
December 6, 2018 06:43
-
-
Save DrynnBavis/27c9dbd72a38e0fc1b5993577a1a081b to your computer and use it in GitHub Desktop.
Returns the lowest common ancestor in a BST
This file contains hidden or 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
| # 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