Bird
Raised Fist0
DSA C#programming~20 mins

Path Sum Root to Leaf in Binary Tree in DSA C# - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Path Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of path sum check for a simple tree
What is the output of the following C# code that checks if a binary tree has a root-to-leaf path with sum 22?
DSA C#
public class TreeNode {
    public int val;
    public TreeNode left, right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public bool HasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        if (root.left == null && root.right == null) return root.val == targetSum;
        return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
    }
}

// Tree construction
TreeNode root = new TreeNode(5,
    new TreeNode(4,
        new TreeNode(11,
            new TreeNode(7),
            new TreeNode(2)
        ),
        null
    ),
    new TreeNode(8,
        new TreeNode(13),
        new TreeNode(4,
            null,
            new TreeNode(1)
        )
    )
);

Solution sol = new Solution();
System.Console.WriteLine(sol.HasPathSum(root, 22));
ACompilation error
BFalse
CTrue
DRuntime exception
Attempts:
2 left
💡 Hint
Trace the path sums from root to leaves and check if any equals 22.
❓ Predict Output
intermediate
2:00remaining
Output when no path matches the sum
What does the following code print when checking for a path sum of 26 in the given tree?
DSA C#
TreeNode root = new TreeNode(1,
    new TreeNode(2),
    new TreeNode(3)
);
Solution sol = new Solution();
System.Console.WriteLine(sol.HasPathSum(root, 26));
AFalse
BTrue
CNullReferenceException
DCompilation error
Attempts:
2 left
💡 Hint
Check if any root-to-leaf path sums to 26.
🔧 Debug
advanced
2:00remaining
Identify the error in path sum code
What error does this code produce when run?
DSA C#
public bool HasPathSum(TreeNode root, int targetSum) {
    if (root == null) return false;
    if (root.left == null && root.right == null) return root.val == targetSum;
    return HasPathSum(root.left, targetSum - root.val) & HasPathSum(root.right, targetSum - root.val);
}
AAlways returns false incorrectly
BStackOverflowException due to infinite recursion
CCompilation error due to wrong operator
DLogical error: uses bitwise AND instead of logical OR
Attempts:
2 left
💡 Hint
Check the operator used to combine recursive calls.
🧠 Conceptual
advanced
1:00remaining
Number of root-to-leaf paths in a full binary tree of height 3
How many root-to-leaf paths are there in a full binary tree of height 3?
A3
B4
C7
D8
Attempts:
2 left
💡 Hint
A full binary tree has 2 children per node except leaves.
🚀 Application
expert
3:00remaining
Find all root-to-leaf paths with given sum
Which code snippet correctly returns all root-to-leaf paths where the sum of node values equals targetSum?
A
public IList<IList<int>> PathSum(TreeNode root, int targetSum) {
    var res = new List<IList<int>>();
    void DFS(TreeNode node, int sum, List<int> path) {
        if (node == null) return;
        path.Add(node.val);
        sum -= node.val;
        if (node.left == null && node.right == null && sum == 0) {
            res.Add(path.ToList());
        } else {
            DFS(node.left, sum, path);
            DFS(node.right, sum, path);
        }
        path.RemoveAt(path.Count - 1);
    }
    DFS(root, targetSum, new List<int>());
    return res;
}
B
public IList<IList<int>> PathSum(TreeNode root, int targetSum) {
    var res = new List<IList<int>>();
    void DFS(TreeNode node, int sum, List<int> path) {
        if (node == null) return;
        path.Add(node.val);
        sum -= node.val;
        if (node.left == null && node.right == null && sum == 0) {
            res.Add(path);
        } else {
            DFS(node.left, sum, path);
            DFS(node.right, sum, path);
        }
        path.RemoveAt(path.Count - 1);
    }
    DFS(root, targetSum, new List<int>());
    return res;
}
C
public IList<IList<int>> PathSum(TreeNode root, int targetSum) {
    var res = new List<IList<int>>();
    void DFS(TreeNode node, int sum, List<int> path) {
        if (node == null) return;
        path.Add(node.val);
        sum -= node.val;
        if (node.left == null && node.right == null && sum == 0) {
            res.Add(path);
        }
    }
    DFS(root, targetSum, new List<int>());
    return res;
}
D
public IList<IList<int>> PathSum(TreeNode root, int targetSum) {
    var res = new List<IList<int>>();
    void DFS(TreeNode node, int sum, List<int> path) {
        if (node == null) return;
        path.Add(node.val);
        sum -= node.val;
        if (node.left == null && node.right == null && sum == 0) {
            res.Add(new List<int>(path));
        } else {
            DFS(node.left, sum, path);
            DFS(node.right, sum, path);
        }
        path.RemoveAt(path.Count - 1);
    }
    DFS(root, targetSum, new List<int>());
    return res;
}
Attempts:
2 left
💡 Hint
Make sure to add a copy of the path, not the original list, to the result.

Practice

(1/5)
1. What does the "Path Sum Root to Leaf" problem ask you to find in a binary tree?
easy
A. The total number of nodes in the binary tree
B. The maximum depth of the binary tree
C. If there exists a root-to-leaf path with a sum equal to a given target
D. The sum of all node values in the binary tree

Solution

  1. Step 1: Understand the problem statement

    The problem asks to check if any path from the root node down to any leaf node sums up exactly to a given target value.
  2. Step 2: Identify what is being checked

    We are not asked for maximum depth, total nodes, or sum of all nodes, but specifically for a path sum equal to the target.
  3. Final Answer:

    If there exists a root-to-leaf path with a sum equal to a given target -> Option C
  4. Quick Check:

    Path sum check = If there exists a root-to-leaf path with a sum equal to a given target [OK]
Hint: Look for a path from root to leaf matching target sum [OK]
Common Mistakes:
  • Confusing path sum with total tree sum
  • Checking any path, not just root-to-leaf
  • Looking for maximum depth instead
2. Which of the following C# method signatures correctly represents a function to check path sum in a binary tree node class?
easy
A. public bool HasPathSum(TreeNode root, int targetSum)
B. public int HasPathSum(TreeNode root, int targetSum)
C. public void HasPathSum(TreeNode root, int targetSum)
D. public string HasPathSum(TreeNode root, int targetSum)

Solution

  1. Step 1: Determine the return type for path sum check

    The function should return true or false indicating if such a path exists, so return type must be bool.
  2. Step 2: Check method signature correctness

    public bool HasPathSum(TreeNode root, int targetSum) returns bool and takes root node and target sum as parameters, matching the problem requirements.
  3. Final Answer:

    public bool HasPathSum(TreeNode root, int targetSum) -> Option A
  4. Quick Check:

    Return type bool for yes/no check = public bool HasPathSum(TreeNode root, int targetSum) [OK]
Hint: Return bool for yes/no path sum check [OK]
Common Mistakes:
  • Using int or void return type instead of bool
  • Returning string instead of boolean
  • Incorrect parameter types or order
3. Given the following binary tree and targetSum = 22, what will the method HasPathSum(root, 22) return?
    5
   / \
  4   8
 /   / \
11  13  4
/  \      
7    2      1
medium
A. Runtime error
B. true
C. null
D. false

Solution

  1. Step 1: Identify root-to-leaf paths and their sums

    Check paths: 5->4->11->7 = 27, 5->4->11->2 = 22, 5->8->13 = 26, 5->8->4->1 = 18.
  2. Step 2: Check if any path sum equals 22

    Path 5->4->11->2 sums to 22, so the method returns true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Path sum 22 exists = true [OK]
Hint: Sum each root-to-leaf path to find target [OK]
Common Mistakes:
  • Ignoring leaf node condition
  • Summing partial paths not ending at leaf
  • Miscomputing sums of nodes
4. The following C# code attempts to check path sum but has a bug. What is the error?
public bool HasPathSum(TreeNode root, int targetSum) {
    if (root == null) return false;
    if (root.left == null && root.right == null) return root.val == targetSum;
    return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
}
medium
A. No bug; code works correctly
B. Should check for null root after subtracting value
C. Incorrect base case for leaf node check
D. Missing return statement in recursive calls

Solution

  1. Step 1: Analyze base cases and recursion

    Code returns false if root is null, correctly handles leaf node by comparing value to targetSum, and recursively checks left and right subtrees with updated targetSum.
  2. Step 2: Confirm correctness of logic

    All conditions and recursive calls are correct and return statements are present.
  3. Final Answer:

    No bug; code works correctly -> Option A
  4. Quick Check:

    Code logic matches problem requirements = No bug; code works correctly [OK]
Hint: Check base cases and recursive returns carefully [OK]
Common Mistakes:
  • Forgetting to subtract node value from targetSum
  • Missing return keyword in recursion
  • Incorrect leaf node condition
5. You want to find all root-to-leaf paths in a binary tree where the sum of node values equals a target sum. Which approach best extends the path sum check to collect all such paths?
hard
A. Sum all nodes and compare to target sum once traversal ends
B. Use BFS and stop at first path matching the sum
C. Use recursion without tracking path, just return true/false
D. Use DFS with a list to track current path and add to result when sum matches at leaf

Solution

  1. Step 1: Understand the requirement to collect all paths

    We need to find all root-to-leaf paths with sum equal to target, so we must track the current path during traversal.
  2. Step 2: Choose the correct traversal and tracking method

    DFS with a list to store nodes along the current path allows backtracking and collecting all valid paths when leaf and sum conditions are met.
  3. Final Answer:

    Use DFS with a list to track current path and add to result when sum matches at leaf -> Option D
  4. Quick Check:

    Track paths with DFS and list = Use DFS with a list to track current path and add to result when sum matches at leaf [OK]
Hint: Track path nodes during DFS to collect all valid paths [OK]
Common Mistakes:
  • Using BFS which is less natural for path tracking
  • Not tracking path nodes, only sums
  • Stopping at first found path instead of all
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard