简繁EN

LeetCodeNo. 078

[LeetCode with Python] 112. Path Sum

Contents

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 and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:

def doHasPathSum(self, root, total, sum):
if None == root.left and None == root.right:
return sum == (total + root.val)

left= False
right = False
if None != root.left:
left = self.doHasPathSum(root.left, total + root.val, sum)
if False == left and None != root.right: # pruning
right = self.doHasPathSum(root.right, total + root.val, sum)
return left or right

# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if None == root:
return False ###
return self.doHasPathSum(root, 0, sum)

Article link: https://xnerv.wang/en/leetcode-path-sum/