github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/leetcode/path-sum-iii_test.go (about)

     1  package leetcode
     2  
     3  //437. 路径总和 III
     4  //https://leetcode-cn.com/problems/path-sum-iii/
     5  
     6  // 遍历每个节点为起点, 调用一个子过程找到路径和
     7  func pathSum(root *TreeNode, sum int) int {
     8  	if root == nil {
     9  		return 0
    10  	}
    11  	cnt := findNodeSum(root, sum)
    12  	cnt += pathSum(root.Left, sum)
    13  	cnt += pathSum(root.Right, sum)
    14  	return cnt
    15  }
    16  
    17  func findNodeSum(node *TreeNode, num int) int {
    18  	if node == nil {
    19  		return 0
    20  	}
    21  
    22  	ret := 0
    23  	if node.Val == num {
    24  		ret += 1 // 找到了+1
    25  	}
    26  	ret += findNodeSum(node.Left, num-node.Val)
    27  	ret += findNodeSum(node.Right, num-node.Val)
    28  	return ret
    29  }