美文网首页
[LeetCode] Path Sum

[LeetCode] Path Sum

作者: lyy0905 | 来源:发表于2018-03-12 09:54 被阅读0次

    题目

    原题地址

    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.

    思路

    递归查找,每个节点判断一下是否叶子节点,如果是则判断value之和是否与sum相同;如果不是叶子节点,就递归查找它的左右子节点。

    python代码

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            if root == None:
                return False
            if root.left == None and root.right == None:
                # leaf node
                return root.val == sum
            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
    

    Path Sum

    进阶版Path Sum,不仅判断是否存在这样的路径,而是要求给出所有满足要求的路径。
    原题地址

    思路

    总体思想与上一题类似,但是需要增加一个参数list来保存路径,所以需要重新写一个递归函数。注意往list里append值之后要对应的pop,否则后续对list的操作也会反映到最终结果上,因为最终返回的是一个List[List[int]],其中的每个list是浅拷贝。

    python代码

    # 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 search(self, root, sum, ls):
            if root == None:
                return
            if root.left == None and root.right == None:
                # leaf node
                if sum == root.val:
                    ls.append(root.val)
                    self.result.append(ls[:])
                    ls.pop()
            else:
                # not leaf node
                ls.append(root.val)
                self.search(root.left, sum-root.val, ls)
                self.search(root.right, sum-root.val, ls)
                ls.pop()
    
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            self.result = []
            self.search(root, sum, [])
            return self.result
    

    相关文章

      网友评论

          本文标题:[LeetCode] Path Sum

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