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.
1from collections import deque23# Definition for a binary tree node.4# class TreeNode:5# def __init__(self, x):6# self.val = x7# self.left = None8# self.right = None910class Solution:11 def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':12 if root in (None, p, q): return root13 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