LeetCode 236. Lowest Common Ancestor of a Binary Tree

December 5, 2024

This is the last month of my goal toward 150 problems done by 2025. I'll have to pick up more than a few problems this weekend. I have 56 problems remaining.

Solution

1from collections import deque
2
3# Definition for a binary tree node.
4# class TreeNode:
5# def __init__(self, x):
6# self.val = x
7# self.left = None
8# self.right = None
9
10class Solution:
11 def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
12 if root in (None, p, q): return root
13 left, right = [self.lowestCommonAncestor(kid, p, q) for kid in (root.left, root.right)]
14 return root if left and right else left or right

Time complexity is O(n) = n and space complexity is O(h) where the height is h. Best case the height is log(n) as a balanced tree and worst case is n as a skewed tree.

LeetCode 105. Construct Binary Tree from Preoder and Inorder Traversal

LeetCode 103. Binary Tree Zigzag Level Order Traversal