NOTE
Path Sum III
Count downward paths in an integer-valued binary tree whose sum equals a target. Paths need not start at the root or end at a leaf.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given a binary tree, each node stores an integer value.
Find the total number of paths whose sum equals the given value.
A path does not need to start at the root or end at a leaf, but it must go downward (from parent to child only).
The binary tree contains at most 1000 nodes, and node values are integers in the range [-1000000,1000000].
2. Approach
- Approach 1
- Recursion
- Count paths that include
rootand paths that do not includeroot
3. Implementation
3.1. Recursion
func pathSum(root *TreeNode, sum int) int {
if root == nil {
return 0
}
return pathSumDFS(root, sum) + pathSum(root.Left, sum) + pathSum(root.Right, sum)
}
func pathSumDFS(root *TreeNode, sum int) int {
if root == nil {
return 0
}
count := 0
if root.Val == sum {
count += 1
}
count += pathSumDFS(root.Left, sum-root.Val)
count += pathSumDFS(root.Right, sum-root.Val)
return count
}
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub