Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    A path from the top with a given total

    EasyAbout 15 minFull AccessLearn it: Tree Traversals in C#: Recursive and Iterative DFS, BFS Level Order and Stack Depth

    The task

    An approval flow is stored as a binary tree: each node holds the cost one step adds, and a path from the root down to a leaf (a node with no children) is one way a request can travel.

    Complete HasRootToLeafSum(TreeNode? root, int target). Return true if some path from the root down to a leaf has node values that add up to target. Values and the target can be negative. An empty tree (null) has no path. The TreeNode class is given; do not change it.

    Signature

    public static bool HasRootToLeafSum(TreeNode? root, int target)

    Examples

    • tree [7, 3, 9, 1, 4, null, -2], target 11 → true. 7 + 3 + 1 = 11, and 1 is a leaf.
    • tree [1, 2], target 1 → false. The root has a child, so a path must go on to the leaf 2.

    Limits: Up to 5,000 nodes. Trees are written level by level, with null for a missing child.

    The tests check: an empty tree, a single node (it is a leaf), a root that is not a leaf, negative values, a total that is reached at a node that is not a leaf, two paths with the same total, a total beyond int, and a chain of 5,000 nodes.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      // A node of a binary tree. Do not change this class: the tests build trees with it.
      public sealed class TreeNode
      {
          public int Val;
          public TreeNode? Left;
          public TreeNode? Right;
      
          public TreeNode(int val, TreeNode? left = null, TreeNode? right = null)
          {
              Val = val;
              Left = left;
              Right = right;
          }
      }
      
      public static class Solution
      {
          // Returns true when some root-to-leaf path adds up to target.
          public static bool HasRootToLeafSum(TreeNode? root, int target)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.