LeetCode Day 13 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.

Exa…


This content originally appeared on DEV Community and was authored by Flame Chan

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);
    }


This content originally appeared on DEV Community and was authored by Flame Chan


Print Share Comment Cite Upload Translate Updates
APA

Flame Chan | Sciencx (2024-06-21T13:40:46+00:00) LeetCode Day 13 Binary Tree Part 4. Retrieved from https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/

MLA
" » LeetCode Day 13 Binary Tree Part 4." Flame Chan | Sciencx - Friday June 21, 2024, https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/
HARVARD
Flame Chan | Sciencx Friday June 21, 2024 » LeetCode Day 13 Binary Tree Part 4., viewed ,<https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/>
VANCOUVER
Flame Chan | Sciencx - » LeetCode Day 13 Binary Tree Part 4. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/
CHICAGO
" » LeetCode Day 13 Binary Tree Part 4." Flame Chan | Sciencx - Accessed . https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/
IEEE
" » LeetCode Day 13 Binary Tree Part 4." Flame Chan | Sciencx [Online]. Available: https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/. [Accessed: ]
rf:citation
» LeetCode Day 13 Binary Tree Part 4 | Flame Chan | Sciencx | https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.