leetcode-路径总和II(python)
2019-03-23 20:47
190 查看
题目:
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
思想:
二叉树深度遍历+回溯
代码:
class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: pathvalue=0 path=[] result=[] def preorder(node,pathvalue,sum,path,result): if node==None: return pathvalue+=node.val path.append(node.val) if pathvalue==sum and node.left==None and node.right==None: result.append(list(path)) #注意加list preorder(node.left,pathvalue,sum,path,result) preorder(node.right,pathvalue,sum,path,result) pathvalue-=node.val path.pop() preorder(root,pathvalue,sum,path,result) return result
相关文章推荐
- 利用python 完成leetcode 113 路径总和 II
- LeetCode 113. 路径总和 II Python
- 利用python 完成leetcode 112 路径总和
- leetcode 第62题 不同路径, 第63题 不同路径 II, 第64题,最小路径和(python解法)
- LeetCode-113.路径总和II(相关话题:深度优先)
- Leetcode 113. 路径总和 II
- 【LeetCode】#113路径总和II(Path Sum II)
- LeetCode 112. 路径总和 Python
- [Leetcode][python]Best Time to Buy and Sell Stock I/II/III
- leetcode Linked List Cycle II python
- 【python】【leetcode】【算法题目167—Two Sum II - Input array is sorted】
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- Leetcode 80 删除排序数组中的重复项 II Python C++ 史上最详细题解系列
- 利用python 完成 leetcode126 单词接龙 II
- [leetcode, python] Pascal's Triangle II 杨辉三角
- [Leetcode]@python 92. Reverse Linked List II
- leetcode 【 Remove Duplicates from Sorted List II 】 python 实现
- LeetCode-Python-216. 组合总和 III
- [leetcode]N-Queens II @ Python
- 【LeetCode with Python】 Path Sum II