Back to Leetcode Go

112. Path Sum

website/content.en/ChapterFour/0100~0199/0112.Path-Sum.md

1.7.971.2 KB
Original Source

112. Path Sum

Problem

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Problem Summary

Given a binary tree and a target sum, determine whether there exists a path from the root node to a leaf node such that the sum of all node values along this path equals the target sum. Note: A leaf node is a node with no children.

Solution Approach

  • Solve recursively

Code

go

package leetcode

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