Your question is Root-to-Leaf Path Sum. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
RealSelf can model hierarchical review or moderation data as a binary tree of integer scores. Given the root of a binary tree and an integer k, determine whether any path from the root to a leaf has values that sum exactly to k.
A node is a leaf when it has no left or right child. The path must begin at the root and end at a leaf, so stopping at an internal node does not count.
Implement has_path_sum(root, k).
root is either None or a TreeNode with an integer val and optional left and right children.k is an integer target sum.True if at least one root-to-leaf path sums to k; otherwise return False.For test cases, trees are represented as nested objects with val, left, and right fields, where a missing child is null.
def has_path_sum(root, k):