劍指offer面試題34. 二叉樹中和爲某一值的路徑(先序遍歷)(回溯)

題目描述

輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和爲輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。
在這裏插入圖片描述

思路

詳見鏈接

代碼

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) 額外空間。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章