class TreeNode:
def __init__(self,val):
self.val=val
self.left, self.right = None, None
class Solution:
"""
二叉树的路径和 {1,2,4,2,3} 总和是 5 的所有路径
"""
allPath=[]
def binaryTreePathSum(self, root, target):
if root is None: return None
self.recuitPath(root,[root.val])
desPaths=[]
print("get all paths = %s" % self.allPath)
for path in self.allPath:
if sum(path)==target:
desPaths.append(path)
return desPaths
def recuitPath(self, node, halfPath):
if node is None:
return halfPath
if node.left:
leftPath=halfPath.copy()
leftPath.append(node.left.val)
self.recuitPath(node.left, leftPath)
if node.right:
rightPath=halfPath.copy()
rightPath.append(node.right.val)
self.recuitPath(node.right, rightPath)
if node.left is None or node.right is None:
self.allPath.append(halfPath)
if __name__=="__main__":
rootNode = TreeNode(1)
node11=TreeNode(2)
node12=TreeNode(4)
rootNode.left=node11
rootNode.right=node12
node21=TreeNode(2)
node22=TreeNode(3)
node11.left=node21
node11.right=node22
solution=Solution()
pathList=solution.binaryTreePathSum(rootNode,5)
print(pathList)
LintCode 二叉树路径和 Binary Tree
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Find the maximum node in a binary tree, return the node. ...
- 题目:Given a binary tree, return all root-to-leaf paths.返回所...