Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/8fdcd7a83c20470e2871a86e4d1fea20 to your computer and use it in GitHub Desktop.
Save liyunrui/8fdcd7a83c20470e2871a86e4d1fea20 to your computer and use it in GitHub Desktop.
leetcode-treee
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
For each given current node, we need to determine where to search the common ancestor.
Then, we leverage properties of bst.
"""
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
T:O(h) since we only search half of tree
S:O(h) because of recursion stack
"""
def dfs(r):
if max(p.val, q.val) < r.val:
return dfs(r.left)
elif min(p.val, q.val) > r.val:
return dfs(r.right)
else:
return r
return dfs(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment