class TreeNode:
def __init__(self,val):
self.val=val
self.left, self.right = None, None
class Solution:
"""
二叉樹(shù)的路徑和 {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 二叉樹(shù)路徑和 Binary Tree
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
推薦閱讀更多精彩內(nèi)容
- Find the maximum node in a binary tree, return the node. ...
- 題目:Given a binary tree, return all root-to-leaf paths.返回所...
- 作者:嬉皮的西皮 她喜歡被人叫做“小白”。 小白從2005年開(kāi)始健身,十幾年間越發(fā)時(shí)尚健康。 ...
- 人活一輩子,心態(tài)最重要,不要被情緒所困擾。已經(jīng)得到的東西就要好好珍惜,它們不一定會(huì)長(zhǎng)久;一些已經(jīng)失去的東西就要順其...
- 關(guān)于mysql-proxy 配置lua腳本中,有幾個(gè)函數(shù)需要額外記錄下 1、connect_server() — ...