112.E 路径总和

Problem: 112. 路径总和

思路

是否存在从根节点到叶子节点的路径和为target,相当于是否存在从根节点的子节点到叶子节点的路径和为target-root.Val

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, targetSum int) bool {
	if root == nil {
		return false
	}

	if root.Left == nil && root.Right == nil {
		return root.Val == targetSum
	}

	return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val)
}

Last updated

Was this helpful?