题目:
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] ]
思路:
递归求解,只是要保存当前的结果,并且每次递归出来后要恢复递归前的结果,每当递归到叶子节点时就把当前结果保存下来。
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {number} sum * @return {number[][]} */ var pathSum = function(root, sum) { var path=[],res=[]; if(root==null){ return []; } path.push(root.val); getPath(root,sum,path,res); return res; }; function getPath(root,sum,path,res){ path=path.concat(); if(root.left==null&&root.right==null&&root.val==sum){ res.push(path); return; } if(root.left){ path.push(root.left.val); getPath(root.left,sum-root.val,path,res); path.pop(); } if(root.right){ path.push(root.right.val); getPath(root.right,sum-root.val,path,res); path.pop(); } }