劍指offer:二叉樹中和為某一值的路徑(Python)
阿新 • • 發佈:2019-01-09
站在巨人的肩膀上,風景這邊獨好;
親自爬上巨人的肩膀,才知風景為什麼這麼美。
題目描述
輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
解題思路
– 注意到路徑必須為跟節點 –> 沒有左右子樹的葉子節點;定義兩個陣列pathArray、onePath,pathArray用於儲存所有符合條件的路徑,onePath用於儲存當前遍歷的路徑;
– 類似於深度優先搜尋,每遍歷到一個節點,就將其加入到onePath中,並判定是否符合條件:
1. 為葉節點且和等於要求的整數,則將該陣列儲存至pathArray中,並換其他路徑繼續搜尋;
2. 和小於要求的整數,則向當前節點的左右子樹依次深度優先搜尋;
3. 和大於要求的整數,則直接換路搜尋。
程式碼草稿
import copy
class Solution:
def FindPath(self, root, expectNumber):
onePath = []
pathArray = []
self.Find(root, expectNumber, onePath, pathArray)
return pathArray
def Find(self, root, expectNumber, onePath, pathArray):
if root == None:
return pathArray
onePath.append(root.val)
if self.getSum(onePath) == expectNumber and not root.left and not root.right:
pathArray.append(copy.deepcopy(onePath))
elif self.getSum(onePath) < expectNumber:
if root.left != None:
self.Find(root.left, expectNumber, onePath, pathArray)
onePath.pop(-1 )
if root.right != None:
self.Find(root.right, expectNumber, onePath, pathArray)
onePath.pop(-1)
elif self.getSum(onePath) > expectNumber:
onePath.pop(-1)
def getSum(self, array):
sum = 0
for i in array:
sum += i
return sum
為了不讓其他因素干擾到思路,寫程式碼時完全不考慮美觀和簡潔;Python是優雅的,好的程式一定是賞心悅目的。如果程式碼邏輯很醜陋,那一定是自己的問題… 所以現在到了改正自己問題的時候了~:
待優化:
1. 寫三個函式,只為實現一個功能;第一個函式只是為了宣告變數而存在,第二個函式傳入的變數則過多,第三個函式則無存在的必要;
2. 程式碼不夠精煉,陣列元素彈出操作、判斷節點是否為空的操作均出現多次。
優化後的程式碼
class Solution:
def __init__(self):
self.onePath = []
self.PathArray = []
def FindPath(self, root, expectNumber):
if root is None:
return self.PathArray
self.onePath.append(root.val)
expectNumber -= root.val
if expectNumber==0 and not root.left and not root.right:
self.PathArray.append(self.onePath[:])
elif expectNumber>0:
self.FindPath(root.left,expectNumber)
self.FindPath(root.right,expectNumber)
self.onePath.pop()
return self.PathArray
能優化成這個樣子,還是要感謝這篇部落格程式碼寫得夠簡潔啊[捂臉]