JZoffer 二叉樹中和為某一值的路徑

2021-08-20 03:09:41 字數 1089 閱讀 4634

輸入一顆二叉樹和乙個整數,列印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

將當前結點加入路徑中,如果當前結點是葉結點,判斷至當前結點的路徑和是否符合條件,若符合則將路徑加入最終結果。

每一輪遞迴返回到父結點時,當前路徑也應該回退乙個結點。

# -*- coding:utf-8 -*-

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution:

# 返回二維列表,內部每個列表表示找到的路徑

deffindpath

(self, root, expectnumber):

# write code here

# copy code and learn it

ifnot root: # 節點為空則返回空列表

return

ifnot root.left and

not root.right and root.val == expectnumber: # 如果節點為葉節點並且輸入整數為路徑節點之和

return [[root.val]] # 返回包含當前葉節點值的二維列表

res = # 重新重新整理res為空

left = self.findpath(root.left, expectnumber - root.val) # 空列表或者包含當前葉節點值的二維列表

right = self.findpath(root.right, expectnumber - root.val) # 空列表或者包含當前葉節點值的二維列表

for i in left+right: # 若left和right為空則這裡的迴圈不會被執行

return res # 返回最終二維列表或者返回當前節點之下符合條件的所有路徑

二叉樹中和為某一值得路徑

畫圖可以幫助我們理解,舉個簡單的例子可以看出儲存路徑的資料結構實際就是棧,而遞迴呼叫的本質就是壓棧和出棧的過程。include include include include using namespace std struct binarytreenode void findpath binary...

二叉樹中和為某一值的路徑

include include using namespace std struct node void find path node r,int exceptedsum,vector path,int cursum node buildbtree int a,int i void preorder...

二叉樹中和為某一值的路徑

要輸出所有的路徑,必須額外用乙個棧來儲存當前路徑資訊。當訪問到節點a時,節點a的資訊要在訪問a的左右子樹時用到,因而,該資訊必須在遍歷a的左右子樹前加入到棧中,而在遍歷完a的左右子樹後從棧中移除。每訪問乙個節點,就計算當前路徑值 可直接利用父節點的路徑值 當其等於給定值且當前節點是葉子節點時,就列印...