Algorithm


Problem Nmae: 112. Path Sum

problem Link: https://leetcode.com/problems/path-sum/

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

 

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

bool hasPathSum(struct TreeNode *root, int sum) {
    if (root == NULL) {
        return false;
    }
    int remain = sum - root->val;
    
    if (root->left == NULL && root->right == NULL && remain == 0) { /* leaf */
        return true;
    }
    
    if (hasPathSum(root->left, remain) || hasPathSum(root->right, remain)) {
        return true;
    }
    else return false;
}

void printTreePreOrder(struct TreeNode *p) {
    if (p != NULL) {
        printf("%d", p->val);
        printTreePreOrder(p->left);
        printTreePreOrder(p->right);
    }
    else printf("#");
}

int main() {
    struct TreeNode *t = (struct TreeNode *)calloc(4, sizeof(struct TreeNode));
    struct TreeNode *p = t;
    p->val = 1;
    p->left = ++t;
    t->val = -2;
    t->left = t->right = NULL;
    p->right = ++t;
    t->val = 0;
    t->left = t->right = NULL;
    printTreePreOrder(p); printf("\n");

    printf("%d\n", hasPathSum(p, 1)); /* should be true */
    printf("%d\n", hasPathSum(p, 0)); /* should be false */
    printf("%d\n", hasPathSum(p, -1)); /* should be true */

    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22

Output

x
+
cmd
true

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        sum -= root->val;
        if(!sum && !root->left && !root->right) return true;
        return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22

Output

x
+
cmd
true

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean hasPathSum(TreeNode root, int targetSum) {
    if (root == null) {
      return false;
    }
    Queue < Integer> sumQueue = new LinkedList<>();
    Queue nodeQueue = new LinkedList<>();
    sumQueue.add(targetSum - root.val);
    nodeQueue.add(root);
    while (!nodeQueue.isEmpty()) {
      TreeNode removedNode = nodeQueue.remove();
      int removedSum = sumQueue.remove();
      if (removedNode.left == null && removedNode.right == null && removedSum == 0) {
        return true;
      }
      if (removedNode.left != null) {
        nodeQueue.add(removedNode.left);
        sumQueue.add(removedSum - removedNode.left.val);
      }
      if (removedNode.right != null) {
        nodeQueue.add(removedNode.right);
        sumQueue.add(removedSum - removedNode.right.val);
      }
    }
    return false;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,2,3], targetSum = 5

Output

x
+
cmd
false

#4 Code Example with Javascript Programming

Code - Javascript Programming


const hasPathSum = function(root, sum) {
    if (root == null) {
        return false
    }
    const obj = {
        sum: 0
    }
    const res = []
    dfs(root, obj, sum, res)
    return res.indexOf(true) !== -1
};

function dfs(node, obj, target, res) {

    if (node.left == null && node.right == null) {
        obj.sum += node.val
        if (obj.sum === target) {
            res.push(true)
        }
    }
    if (node.left) {
        dfs(node.left, {sum: obj.sum + node.val}, target, res)
    }
    if (node.right) {
        dfs(node.right, {sum: obj.sum + node.val}, target, res)
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,2,3], targetSum = 5

Output

x
+
cmd
false

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root: return False
        sum-=root.val
        if not root.left and not root.right and sum==0: return True
        return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [], targetSum = 0

Output

x
+
cmd
false

#6 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _112_PathSum
    {
        public bool HasPathSum(TreeNode root, int sum)
        {
            if (root == null) return false;

            sum = sum - root.val;
            if (root.left == null && root.right == null) return sum == 0;
            return HasPathSum(root.left, sum) || HasPathSum(root.right, sum);
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [], targetSum = 0

Output

x
+
cmd
false
Advertisements

Demonstration


Previous
#111 Leetcode Minimum Depth of Binary Tree Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#113 Leetcode Path Sum II Solution in C, C++, Java, JavaScript, Python, C# Leetcode