每日一道算法题--leetcode 112--路径总和--python

【题目描述】

【代码思路】

做这道题首先想到的,就是遍历这棵树的所有根结点到叶结点的路径,将每条路径的和保存在一个list中,最后看list中是否含有题目给定的数据即可。遍历一棵树的所有路径,一定是要用到深度优先,写递归函数的,那么还是抓住一个点去看,就拿5这个结点来看,当递归函数输入的结点是5。

那么我首先是要去判断这个结点是否有左右子树的,用一个变量sum1存放一路总和。我的递归函数是plus(root,sum1);如果有左子树,那么调用plus(root,sum1+5);如果有右子树,那么调用plus(root,sum1+5);有左右子树调用递归函数传入的sum1数值应该是一致的,都是sum1+root.val。

        if root.left:
            self.plus(root.left,sum1+root.val)
        if root.right:
            self.plus(root.right,sum1+root.val)
复制代码

如果这个结点没有左右子树了,说明是叶结点了,那么就直接加上该叶结点的数值,把这个sum1存在list中就好了。

if not root.left and not root.right:
    sum1+=root.val
    print "叶结点:",root.val,"sum1=",sum1
    self.sum_list.append(sum1)
复制代码

在主调函数中调用这个plus递归函数,我定义sum_list为类的一个属性,所以在类内部可直接通过self.sum_list读写。

def __init__(self):
    self.sum_list=[]
复制代码

在主调函数中再判断一下,sum是否包含在sum_list中即可

def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """ 
        sum1=0
        if not root:return False
        self.plus(root,sum1)
        return sum in self.sum_list
复制代码

【源代码】

# 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 __init__(self):
        self.sum_list=[]
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """ 
        sum1=0
        if not root:return False
        self.plus(root,sum1)
        return sum in self.sum_list
    def plus(self,root,sum1):
        print "执行plus(",root.val,sum1,")"
        if not root.left and not root.right:
            sum1+=root.val
            print "叶结点:",root.val,"sum1=",sum1
            self.sum_list.append(sum1)
        if root.left:
            self.plus(root.left,sum1+root.val)
        if root.right:
            self.plus(root.right,sum1+root.val)
        return False
复制代码

【递归过程重现】

为了更好理解,我以一棵树为例,将递归过程打印出来。树为:

执行源代码,递归过程为:

执行plus( 5,0 )
执行plus( 4,5 )
执行plus( 11,9 )
执行plus( 7,20 )
叶结点: 7 sum1= 27
执行plus( 2,20 )
叶结点: 2 sum1= 22
执行plus( 8,5 )
执行plus( 13,13 )
叶结点: 13 sum1= 26
执行plus( 4,13 )
执行plus( 1,17 )
叶结点: 1 sum1= 18
复制代码

猜你喜欢

转载自juejin.im/post/5c99c907e51d455a7e7734dc
今日推荐