Here is the full interview question "Coding - Lowest Common Ancestor of a Binary Tree" asked at Uber:
Problem Statement: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on LeetCode, the lowest common ancestor of two nodes p and q is the lowest node in the tree that has both p and q as descendants (where we allow a node to be a descendant of itself).
Examples:
Given binary tree: 3,5,1,6,2,0,8,#,#,7,4, and nodes p = 5 and q = 1.
3 / \ 5 1 / \ / \ 6 2 0 8
Return the LCA of nodes 5 and 1, which is 3.
Given binary tree: 3,5,1,6,2,0,8,#,#,7,4, and nodes p = 5 and q = 4.
3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4
Return the LCA of nodes 5 and 4, which is 1.
Given binary tree: 1,2, and nodes p = 2 and q = 2.
1 \ 2
Return the LCA of nodes 2 and 2, which is 2.
Constraints:
[2, 10^4].-10^9 <= Node.val <= 10^9Node.val are unique.Hints:
null, return null.Solution: Here's a Python solution using recursion: `python 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': if not root or root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left:
return right
if not right:
return left
return root
` This solution has a time complexity of O(n), where n is the number of nodes in the tree, and a space complexity of O(h), where h is the height of the tree.