題目描述
輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和爲輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。
思路
代碼
class Solution:
def pathSum(self, root:TreeNode, sum:int)->List[List[int]]:
res, path = [], []
def recur(root, tar):
if not root:
return
path.append(root.val)
tar -= root.val
if tar == 0 and not root.left and not root.right:
res.append(list(path))
recur(root.left, tar)
recur(root.right, tar)
path.pop()
recur(root, sum)
return res
複雜度
時間複雜度 O(N):NN爲二叉樹的節點數,先序遍歷需要遍歷所有節點。
空間複雜度 O(N) :最差情況下,即樹退化爲鏈表時,path 存儲所有樹節點,使用 O(N) 額外空間。