Tree - 112. Path Sum

时间:2022-07-25
本文章向大家介绍Tree - 112. Path Sum,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

112. Path Sum

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.

思路:

题目意思是问根节点叶子节点的路径有没有求和之后等于sum,很简单的题目,和257题类似,递归求解。

代码:

go:

/**

 * Definition for a binary tree node.

 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, sum int) bool {
    var res bool
    if root == nil {
        return false
    }
    recursive(root, &res, root.Val, sum)
    return res
}

func recursive(node *TreeNode, res *bool, val int, sum int) {
    if node.Left == nil && node.Right == nil && val == sum {
        *res = true
    } 
    
    if node.Left != nil {
        recursive(node.Left, res, node.Left.Val + val, sum)
    }
    
    if node.Right != nil {
        recursive(node.Right, res, node.Right.Val + val, sum)
    }
}