C# || How To Determine If Binary Tree Root To Leaf Path Sum Exists Using C#

The following is a module with functions which demonstrates how to determine if a binary tree root to leaf path sum exists using C#.


1. Has Path Sum – Problem Statement

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:

Example 1


Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true

Example 2:

Example 2


Input: root = [1,2,3], targetSum = 5
Output: false

Example 3:


Input: root = [1,2], targetSum = 0
Output: false


2. Has Path Sum – Solution

The following is a solution which demonstrates how to determine if a binary tree root to leaf path sum exists.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


true
false
false

Was this article helpful?
👍 YesNo

Leave a Reply