Algo-Sim › Binary Trees & BST

Path Sum

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Subtract each node from the target on the way down; a path works if a leaf leaves exactly 0.

Problem

Given the root of a binary tree and targetSum, return true if some path from the root down to a leaf has values that add up to targetSum. A leaf is a node with no children.

Constraints

Edge cases to test

Follow-up questions

What if paths can start and end anywhere?
Prefix sums along the root path in a hash map (Path Sum III): O(n).
How do you return every path?
Backtrack with one path list (Path Sum II).

Solution

Java

public boolean hasPathSum(TreeNode root, int targetSum) {
    if (root == null) return false;
    int remaining = targetSum - root.val;
    if (root.left == null && root.right == null) return remaining == 0;
    if (hasPathSum(root.left, remaining)) return true;
    return hasPathSum(root.right, remaining);
}

Python

def has_path_sum(root, target_sum):
    if not root:
        return False
    remaining = target_sum - root.val
    if not root.left and not root.right:
        return remaining == 0
    if has_path_sum(root.left, remaining):
        return True
    return has_path_sum(root.right, remaining)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool hasPathSum(TreeNode *root, int targetSum) {
        if (root == nullptr)
            return false;
        int remaining = targetSum - root->val;
        if (root->left == nullptr && root->right == nullptr)
            return remaining == 0;
        if (hasPathSum(root->left, remaining))
            return true;
        return hasPathSum(root->right, remaining);
    }
};

More Binary Trees & BST problems