Created
February 17, 2021 05:57
-
-
Save liyunrui/8fdcd7a83c20470e2871a86e4d1fea20 to your computer and use it in GitHub Desktop.
leetcode-treee
This file contains 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: | |
""" | |
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