官網題目敘述:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
附上過關:
這題把上一題的結果收集起來就好,這邊要知道一點就是傳遞陣列物件時是傳遞參考物件,要知道哪些是要傳參考那些只是想傳值就好,把上一題答案加上一點小修改就好。
var pathSum = function(root, sum) { if(root===null)return []; let results = []; hasPathSum(root,sum,[],results); return results; var hasPathSum = function(root, sum , path , results) { if(root===null)return false; sum-=root.val; path.push(root.val); if(sum===0 && (root.left===null && root.right===null)){ results.push(path); return false; } return hasPathSum(root.left , sum,path.slice(),results) || hasPathSum(root.right,sum,path.slice(),results); };
全站熱搜