您的位置:首页 > 编程语言 > Java开发

leetcode:Path Sum II 【Java】

2016-03-08 10:15 405 查看
一、问题描述

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.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> segRes;//保存中间结果
        //每次迭代都独立创建一个list保存本次搜索结果
        pathSum(root, sum, new ArrayList<Integer>(), result);
        return result;
    }
    public void pathSum(TreeNode root, int gap, List<Integer> segRes, List<List<Integer>> result){
        if(root == null){
            return;//本轮递归结束
        }
        segRes.add(root.val);
        
        if(root.left == null && root.right == null){ //叶子结点
            if(gap == root.val){//该叶子结点值等于最后的差值
                result.add(segRes);
                return; //本轮递归结束
            }
        }
        
        //注意是带参数的new ArrayList<Integer>(segRes),需要携带前面的中间结果
        pathSum(root.left, gap - root.val, new ArrayList<Integer>(segRes), result);
        pathSum(root.right, gap - root.val, new ArrayList<Integer>(segRes), result);
        
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: