回溯和深度遍历
Go版本:
func pathSum(root *TreeNode, targetSum int)(res int) {
if root==nil{
return
}
res=rootSum(root,targetSum)
res+=pathSum(root.Left,targetSum)
res+=pathSum(root.Right,targetSum)
return ;
}
func rootSum(root *TreeNode,targetSum int)(res int){
if root==nil{
return 0
}
value:=root.Val
if value==targetSum{
res++;
}
res+= rootSum(root.Left,targetSum-value)
res+=rootSum(root.Right,targetSum-value)
return ;
}
网友评论