首页 > 其他 > 详细

【树】Path Sum II(递归)

时间:2016-01-29 11:55:06      阅读:150      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!