美文网首页
[Tree]113. Path Sum II

[Tree]113. Path Sum II

作者: 野生小熊猫 | 来源:发表于2019-02-23 05:30 被阅读0次
  • 分类:Tree
  • 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
  • 空间复杂度: O(h) 树的节点的深度

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: 'TreeNode', sum: 'int') -> 'List[List[int]]':
        res=[]
        if root==None:
            return res
        self.helper(root,res,[],sum)
        return res
    
    def helper(self,root,res,my_list,sum_):
        remain=sum_-root.val
        my_list.append(root.val)
        if root.left==None and root.right==None:
            if remain==0:
                res.append(my_list.copy())
            my_list.pop()
            return
        elif root.left==None:
            self.helper(root.right,res,my_list,remain)
        elif root.right==None:
            self.helper(root.left,res,my_list,remain)
        else:
            self.helper(root.left,res,my_list,remain)
            self.helper(root.right,res,my_list,remain)
        my_list.pop()

讨论:

1.记住,return之前要把错误的那个数pop出来
2.左子树和右子树因为不同所以也要pop出来

相关文章

网友评论

      本文标题:[Tree]113. Path Sum II

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