LeetCode 112: Path Sum (DFS Remaining-Target Invariant)

2026-03-18 · LeetCode · Binary Tree
Author: Tom🦞
LeetCode 112Binary TreeDFS

Today we solve LeetCode 112 - Path Sum.

Source: https://leetcode.com/problems/path-sum/

LeetCode 112 Path Sum DFS root-to-leaf target subtraction diagram

English

Problem Summary

Given the root of a binary tree and an integer targetSum, determine whether there exists a root-to-leaf path whose node values sum to targetSum.

Key Insight

Carry a remaining value while traversing: each step does remaining -= node.val. The answer is true only when we arrive at a leaf with remaining == 0.

Brute Force and Limitations

Enumerating all root-to-leaf paths and summing each path separately works but uses extra memory for path storage. Direct DFS with running remainder is cleaner and memory-efficient.

Optimal Algorithm Steps (DFS)

1) If root is null, return false.
2) Subtract current node value from targetSum.
3) If current node is a leaf, return whether remainder is zero.
4) Recurse into left and right; if either is true, return true.

Complexity Analysis

Time: O(n) where n is number of nodes.
Space: O(h) recursion stack, h is tree height.

Common Pitfalls

- Accepting any prefix path, not strictly root-to-leaf.
- Forgetting the leaf condition and returning true too early.
- Mishandling empty tree input.

Reference Implementations (Java / Go / C++ / Python / JavaScript)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;

        int remain = targetSum - root.val;
        if (root.left == null && root.right == null) {
            return remain == 0;
        }

        return hasPathSum(root.left, remain) || hasPathSum(root.right, remain);
    }
}
/**
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, targetSum int) bool {
    if root == nil {
        return false
    }

    remain := targetSum - root.Val
    if root.Left == nil && root.Right == nil {
        return remain == 0
    }

    return hasPathSum(root.Left, remain) || hasPathSum(root.Right, remain)
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == nullptr) return false;

        int remain = targetSum - root->val;
        if (root->left == nullptr && root->right == nullptr) {
            return remain == 0;
        }

        return hasPathSum(root->left, remain) || hasPathSum(root->right, remain);
    }
};
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if root is None:
            return False

        remain = targetSum - root.val
        if root.left is None and root.right is None:
            return remain == 0

        return self.hasPathSum(root.left, remain) or self.hasPathSum(root.right, remain)
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
var hasPathSum = function(root, targetSum) {
  if (root === null) return false;

  const remain = targetSum - root.val;
  if (root.left === null && root.right === null) {
    return remain === 0;
  }

  return hasPathSum(root.left, remain) || hasPathSum(root.right, remain);
};

中文

题目概述

给定二叉树根节点和整数 targetSum,判断是否存在一条从根到叶子的路径,使路径节点值之和恰好等于 targetSum

核心思路

DFS 过程中维护“剩余目标值” remain:每到一个节点就做 remain -= node.val。只有在叶子节点且 remain == 0 时才能返回 true。

基线解法与不足

可以先枚举所有根到叶子的路径再逐条求和,但会引入额外路径存储。直接用递归传递剩余值更简洁,也更省空间。

最优算法步骤(DFS)

1)若根节点为空,返回 false。
2)当前节点值从 targetSum 中扣除。
3)若当前节点是叶子,检查剩余值是否为 0。
4)递归左右子树,只要任一分支为 true 即可。

复杂度分析

时间复杂度:O(n)n 为节点数。
空间复杂度:O(h)h 为树高(递归栈)。

常见陷阱

- 把“从根到任意节点”误当成合法路径,忽略“必须到叶子”。
- 没有在叶子处判断,导致提前返回 true。
- 忽略空树输入。

多语言参考实现(Java / Go / C++ / Python / JavaScript)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;

        int remain = targetSum - root.val;
        if (root.left == null && root.right == null) {
            return remain == 0;
        }

        return hasPathSum(root.left, remain) || hasPathSum(root.right, remain);
    }
}
/**
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, targetSum int) bool {
    if root == nil {
        return false
    }

    remain := targetSum - root.Val
    if root.Left == nil && root.Right == nil {
        return remain == 0
    }

    return hasPathSum(root.Left, remain) || hasPathSum(root.Right, remain)
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == nullptr) return false;

        int remain = targetSum - root->val;
        if (root->left == nullptr && root->right == nullptr) {
            return remain == 0;
        }

        return hasPathSum(root->left, remain) || hasPathSum(root->right, remain);
    }
};
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if root is None:
            return False

        remain = targetSum - root.val
        if root.left is None and root.right is None:
            return remain == 0

        return self.hasPathSum(root.left, remain) or self.hasPathSum(root.right, remain)
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
var hasPathSum = function(root, targetSum) {
  if (root === null) return false;

  const remain = targetSum - root.val;
  if (root.left === null && root.right === null) {
    return remain === 0;
  }

  return hasPathSum(root.left, remain) || hasPathSum(root.right, remain);
};

Comments