DEV Community

Flame Chan
Flame Chan

Posted on

LeetCode Day 14 Binary Tree Part 4

LeetCode No. 112. 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:

Image description

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.

Original Page

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null){
            return false;
        }
        return sumOfPath(root, 0, targetSum);
    }

    public boolean sumOfPath(TreeNode cur, int sum, int target){
        if(cur == null){
            return false;
        }
        sum += cur.val;

        if(cur.left == null && cur.right == null){
            return sum==target;
        }

        return sumOfPath(cur.left, sum, target) || sumOfPath(cur.right,sum, target);
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)