Problem
Problem page: https://leetcode.com/problems/path-sum/
Topics: Tree, Depth-first Search
Difficulty: Easy
Similar problems: (M) Path Sum II, (H) Binary Tree Maximum Path Sum, (M) Sum Root to Leaf Numbers
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path
5->4->11->2which sum is 22.
Analysis
It's a simple recursive algorithm. But if the tree is empty, we have to return False no matter what sum is, even if it's 0. Also, since we only need to know whether a solution exists, we can skip the right subtree if we find that left already has a solution.
But there may be negative numbers, so we can't prune a branch just because the path sum is already greater than the given sum.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-path-sum/
