C# || How To Get All Root To Leaf Binary Tree Paths Equal To Path Sum Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to get all the root to leaf binary tree paths equal to path sum using C#.

1. Root To Leaf Path Sum – Problem Statement

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. 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,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22

Example 2:

Example 2

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

Example 3:

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

2. Root To Leaf Path Sum – Solution

The following is a solution which demonstrates how to get all the root to leaf binary tree paths equal to path sum.

The main idea here is that the sum at each level for each path is calculated until we reach the end of the root-to-leaf.

A list is used to store the node value at each level. When the next level is explored, the value is appended to the list, and the process continues.

When we reach the end of the leaf, we check to see if the target value has been reached. If so, we add the node values that make up the path to the result list.

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:


Was this article helpful?
👍 YesNo

Leave a Reply