通过分解为子问题来求解; 1.首先我们要找和为sum的路径 2.当我们遍历了当前节点后,sum的值就变成了sum-curVal,这样问题就转化为求解子问题 3.结束条件很明显,必须是当前节点值等于当前sum值,并且当前节点是叶子节点,也就是当前节点的左右节点都为空
* @description: 112. Path Sum
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that
adding up all the values along the path equals targetSum.
A leaf is a node with no children.
* @return: 是否有一条路径节点之和等于目标值
* @author: kami
* @关键词:回溯
* @date: 2021/7/5 9:26
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
if root.Val == targetSum && root.Left == nil && root.Right == nil {
return true
}
targetSum -= root.Val
return hasPathSum(root.Left, targetSum) || hasPathSum(root.Right, targetSum)
}