How to Find a Root‑to‑Leaf Path Matching a Target Sum in a Binary Tree

This article explains how to determine whether a binary tree contains a root‑to‑leaf path whose node values sum to a given target, outlines the recursive subtraction method, and provides a complete C implementation of the algorithm.

JavaEdge
JavaEdge
JavaEdge
How to Find a Root‑to‑Leaf Path Matching a Target Sum in a Binary Tree

Description

Given a binary tree and an integer target sum, determine whether there exists a path from the root node to any leaf node such that the sum of the node values along that path equals the target sum. A leaf is defined as a node without children, and the path must terminate at a leaf.

Analysis

The algorithm subtracts the current node's value from the remaining target sum while traversing from the root. When a leaf node is reached, the remaining sum is checked; if it is zero, a valid path has been found. The process recurses on left and right sub‑trees.

Solution

bool hasPathSum(struct TreeNode *root, int sum) {
    if (root == NULL) {
        return false;
    }
    sum -= root->val;
    if (root->left == NULL && root->right == NULL) {
        return sum == 0;
    } else {
        return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithminterviewbinary treeRecursionC programmingpath sum
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.