1644. Lowest Common Ancestor of a Binary Tree II
LCA problem
# 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':
self.node = None
def dfs(node, p , q):
if not node:
return 0
left = dfs(node.left, p, q)
right = dfs(node.right, p, q)
current = 1 if node == p or node == q else 0
if not self.node and left + right + current == 2:
self.node = node
return left+right+current
dfs(root, p, q)
return self.node