码迷,mamicode.com
首页 > 其他好文 > 详细

【树】Path Sum II(递归)

时间:2016-01-29 11:56:46      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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();
    }
}

 

【树】Path Sum II(递归)

标签:

原文地址:http://www.cnblogs.com/shytong/p/5168292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!