437. Path Sum III


DFS - brute force
把所有子樹都計算一次, 所以跑 以根為起點的樹 + 以左子樹根為起點的樹 + 以右子樹根為起點的樹

因為這樣就變成嵌套的走訪
所以 time : 最差 O(n^2), BST: O(nlogn)
space: O(n)
2. HashMap(presum, path count) + backtracking
如何不走訪所有的 subtree?
use memories 的技巧,
以 10, 5, 3 這例子, 走訪時計算 presum & path count
(10,1), (15,1), 18 走到 18
(18 - target(8)) = 10 exists in map , 代表有路徑符合我們的 targetSum
so path count = map.get(10)'; map's count record how many path sum count we have
then recursive do node.left & node.right
所以就假設以目前的 sum, 去走左右, 所以先 map sum, count+1
最後在 backtracking 回來
at last, need to do a backtracking, remove the last count

idea like subarray sum equals k, just this one is tree style
time: O(n)
space: O(n)
global variable
dfs sum can show all the sum in a tree

Last updated
Was this helpful?