1
# Definition for a binary tree node.
# class TreeNode(object):
#     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
        """
        #ref http://bookshadow.com/weblog/2016/10/23/leetcode-path-sum-iii/
        def traverse(root, sum):
            """
            :rtype: int
            return the number of paths connecting to root and has sum equals to sum
            """
            if not root:
                return 0
            return (root.val==sum) + traverse(root.left, sum-root.val) + traverse(root.right, sum-root.val)


        if not root:
            return 0
        ans = 0

        ans += traverse(root, sum)
        #if not start from root
        ans += self.pathSum(root.left, sum) + self.pathSum(root.right, sum)

        return ans

In the python code above, why when using function pathSum recursively, there has to be self.pathSum, but when using inner function "traverse" recursively, there is no "self." prefix before calling traverse recursively?

yuhengd
  • 343
  • 3
  • 10
  • 1
    The traverse is a function and pathSum is a method of class Solution. You need to know the difference between function and method: http://stackoverflow.com/questions/155609/difference-between-a-method-and-a-function – Ke Li Apr 11 '17 at 02:57
  • Got it. thanks Ke Li! This is helpful and apparently I am missing a lot of python fundamentals here. – yuhengd Apr 11 '17 at 03:03

0 Answers0