Created
August 14, 2020 21:05
-
-
Save shamod/ec26497dbf4178d6255a9ff7ec4bb1f2 to your computer and use it in GitHub Desktop.
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
class Solution(object): | |
def lowestCommonAncestor(self, root, p, q): | |
def findPath(root, x, res): | |
if not root: return False | |
res.append(root.val) | |
if root.val == x: | |
return True | |
if findPath(root.left, x, res) or findPath(root.right, x, res): | |
return True | |
res.pop() | |
return False | |
pres, qres = [],[] | |
curr = root | |
findPath(curr, p.val, pres) | |
curr = root | |
findPath(curr, q.val, qres) | |
pi, qi = 0, 0 | |
while pi < len(pres) and qi < len(qres): | |
p_elem, q_elem = pres[pi], qres[qi] | |
if p_elem != q_elem: | |
break | |
pi += 1 | |
qi += 1 | |
return TreeNode(pres[pi - 1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment