Leetcode-Easy 437. Path Sum III

101. Symmetric Tree

  • 描述:
    给定一个二叉树和一个目标和,求满足和为目标值的路径个数


    Leetcode-Easy 437. Path Sum III_第1张图片
  • 思路:
    dfs 深度优先搜索
  • 代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        self.res = 0
        self.helper(root,sum)
        return self.res
    
    def dfs(self,root,sum,count,res):
        if not root:
            return
        count += root.val
        if count == sum:
            self.res += 1
        self.dfs(root.left,sum,count,self.res)
        self.dfs(root.right,sum,count,self.res)
    
    def helper(self,root,sum):
        if not root:
            return
        self.dfs(root,sum,0,self.res)
        self.helper(root.left,sum)
        self.helper(root.right,sum)

你可能感兴趣的:(Leetcode-Easy 437. Path Sum III)