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.
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);
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
