Lowest Common Ancestor of a Binary Tree LeetCode solution in Python
1# Runtime: 197 ms (Top 13.70%) | Memory: 26.4 MB (Top 30.94%)2class Solution:3# @param {TreeNode} root4# @param {TreeNode} p5# @param {TreeNode} q6# @return {TreeNode}7def lowestCommonAncestor(self, root, p, q):8# escape condition9if (not root) or (root == p) or (root == q):10return root11# search left and right subtree12left = self.lowestCommonAncestor(root.left, p, q)13right = self.lowestCommonAncestor(root.right, p, q)14if left and right:15# both found, root is the LCA16return root17return left or right