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%)
2
class Solution:
3
# @param {TreeNode} root
4
# @param {TreeNode} p
5
# @param {TreeNode} q
6
# @return {TreeNode}
7
def lowestCommonAncestor(self, root, p, q):
8
# escape condition
9
if (not root) or (root == p) or (root == q):
10
return root
11
# search left and right subtree
12
left = self.lowestCommonAncestor(root.left, p, q)
13
right = self.lowestCommonAncestor(root.right, p, q)
14
if left and right:
15
# both found, root is the LCA
16
return root
17
return left or right

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0