Middle-题目75:113. Path Sum II

原创 2016年05月31日 16:54:07

题目原文:
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]
]
题目大意:
给出一个二叉树和目标和值,输出从根节点到叶子节点的路径为目标和值的所有路径。
题目分析:
还是一个回溯法,backtrack(List<List<Integer>> list, List<Integer> sublist, TreeNode root, int sum)维护搜索过程,其中sum记录还剩下的和值,如果sum恰好为当前节点值且当前节点是叶子节点(想想为什么不能是root==null的时候停止?这样每个路径会添加两遍),则停止搜索,否则递归向子树搜索。
源码:(language:java)

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        if(root!=null)
            backtrack(list, new ArrayList<Integer>(), root, sum);
        return list;
    }
    private void backtrack(List<List<Integer>> list, List<Integer> sublist, TreeNode root, int sum) {

            sublist.add(root.val);  
            if(sum-root.val == 0 && root.left == null && root.right == null)
                list.add(new ArrayList<Integer>(sublist));
            if(root.left!=null)
                backtrack(list, sublist, root.left, sum-root.val);
            if(root.right!=null)
                backtrack(list, sublist, root.right, sum-root.val);
            sublist.remove(sublist.size()-1);

    }
}

成绩:
3ms,beats 14.57%,众数3ms,51.99%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

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 113, Medium] Path sum II

[Leetcode 113, Medium] Path sum II

56. Merge Intervals\113. Path Sum II\211. Add and Search Word - Data structure design

Merge Intervals 题目描述 代码实现 Path Sum II 题目描述 代码实现56. Merge Intervals题目描述Given a collection of interval...

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】113. Path Sum II 基于Java和C++的解法及分析

113. Path Sum II  Total Accepted: 80509 Total Submissions: 284188 Difficulty: Medium Given...

LeetCode 113: Path Sum II

Path Sum IIGiven a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals t...

<LeetCode OJ> 112/113. Path Sum(I / II)

112. Path Sum My Submissions Question Total Accepted: 85016 Total Submissions: 278387 Difficulty...

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 ...

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 113. Path Sum II(路径和)

原题网址:https://leetcode.com/problems/path-sum-ii/ Given a binary tree and a sum, find all root-to-l...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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