Topic:
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 sum = 22
and,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
Ideas:
Recursive solution, just to save the current results, and each recursive to restore the results before recursion, each time recursive to the leaf node when the current results are saved.
/** 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[][]}*/varPathsum =function(root, sum) {varpath=[],res=[]; if(root==NULL){ return []; } path.push (Root.val); GetPath (Root,sum,path,res); returnRes;};functionGetPath (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 (); }}
"Tree" Path Sum II (Recursive)