美文网首页
[easy+][Tree]112. Path Sum

[easy+][Tree]112. Path Sum

作者: 小双2510 | 来源:发表于2017-11-10 00:05 被阅读0次

    path sum 有好几题,是一个系列。

    原题是:

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,
    5
    /
    4 8
    / /
    11 13 4
    / \
    7 2 1
    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    思路是:

    递归函数,上一层和下一层的沟通通道,如果是从上到下,通过传入参数;如果是从下到上,通过函数返回值。
    我们把从root开始的节点的和,sumPath,作为参数,一路传递下去,在函数中,直接和目标值target相比较,相同就返回True, 不相同就返回False.
    同时做这个比较判断时,当前这个节点需要为叶子节点。否则,继续迭代到下一层。

    代码是:

    # 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 hasPathSum(self, root, target):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            if root == None:
                return False
            else:
                return self.helper(root,0,target)
            
        def helper(self,root,sumPath,target):
            
            sumPath = sumPath + root.val
            if not(root.left or root.right):
                if sumPath == target:
                    return True
            else:
                if root.left and self.helper(root.left, sumPath,target):
                    return True
                if root.right and self.helper(root.right, sumPath,target):
                    return True
                    
            return False
    

    相关文章

      网友评论

          本文标题:[easy+][Tree]112. Path Sum

          本文链接:https://www.haomeiwen.com/subject/lbdvmxtx.html