Lowest Common Ancestor of a Binary Tree
https://leetcode.com/explore/learn/card/data-structure-tree/133/conclusion/932/
# 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: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(node,p,q):
if node == None:
return
if node.val == p.val or node.val == q.val:
return node
l = dfs(node.left,p,q)
r = dfs(node.right,p,q)
if l and r:
return node
if l:
return l
return r
return dfs(root,p,q)Last updated