leetcode Path Sum II

原创 2016年06月01日 17:10:53

题目链接

递归回溯

/**
 * 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 LinkedList<List<Integer>>();
        List<Integer> tempResult=new LinkedList<Integer>();
        help(root, sum, 0, result, tempResult);
        return result;
    }

    public void help(TreeNode root,int sum,int currentsum,List<List<Integer> >result,List<Integer> tempResult)
    {
        if(root==null)
        {
            return;
        }
        tempResult.add(root.val);
        currentsum+=root.val;
        if(root.left==null&&root.right==null)
        {
            if(currentsum==sum)
            {
                List<Integer> clone=new LinkedList<Integer>();
                clone.addAll(tempResult);
                result.add(clone);
            }

        }

        if(root.left!=null)
        {
            help(root.left, sum, currentsum, result, tempResult);
        }
        if(root.right!=null)
        {
            help(root.right, sum, currentsum, result, tempResult);
        }

        tempResult.remove(tempResult.size()-1);
        return;
    }
}

相关文章推荐

【leetcode】path-sum-ii

huale //2014年8月23日11:16:49 //2014年8月23日11:45:25 //修改上个代码即可,在处理返回值时浪费很长时间 #include #include u...

[leetcode]24 Path Sum II

题目链接:https://leetcode.com/problems/path-sum-ii/ Runtimes:93ms 1、问题 Given a binary tree and a sum,...
  • shawjan
  • shawjan
  • 2015年03月11日 13:45
  • 259

【LeetCode】path-sum i&ii

题干path-sum iGiven a binary tree and a sum, determine if the tree has a root-to-leaf path such that a...

LeetCode 1.Minimum Path Sum 2.Unique Paths I and II

大家好,我是刘天昊,快到端午节了,今天说两道动态规划的题目(话说动规真的挺难的) 当然这三题是一样的解体思路先看Unique Paths  A robot is located a...

[Leetcode 113, Medium] Path sum II

[Leetcode 113, Medium] Path sum II

LeetCode | Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su...

Leetcode[113]-Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given su...

LeetCode 62/63/120/64 Unique PathsI/II Triangle/Min sum Path/Rectangle Area--DP

一:unique Path 题目: A robot is located at the top-left corner of a m x n grid (marked 'Start' in the ...

LeetCode Solutions : Path Sum I & II

Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi...
  • lviiii
  • lviiii
  • 2014年09月15日 16:23
  • 822

【LeetCode】113. Path Sum II 基于Java和C++的解法及分析

113. Path Sum II  Total Accepted: 80509 Total Submissions: 284188 Difficulty: Medium Given...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode Path Sum II
举报原因:
原因补充:

(最多只允许输入30个字)