leetCode练习(113)

来源:互联网 发布:快递群发短信软件 编辑:程序博客网 时间:2024/06/05 03:14

题目:Path Sum II

难度:medium

问题描述:

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

解题思路:

使用DFS,存入每个符合条件的list即可。

代码如下:

public class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> res=new ArrayList<>();        if(root==null){            return res;        }        DFS(root,sum,res,new ArrayList<Integer>());        return res;    }    private void DFS(TreeNode root,int sum,List<List<Integer>> res,List<Integer> list){if(root.left!=null){list.add(root.val);DFS(root.left,sum-root.val,res,list);list.remove(list.size()-1);if(root.right!=null){list.add(root.val);DFS(root.right,sum-root.val,res,list);list.remove(list.size()-1);}}else if(root.right!=null){list.add(root.val);DFS(root.right,sum-root.val,res,list);list.remove(list.size()-1);}else{if(sum==root.val){List<Integer> temp=new ArrayList<>(list);temp.add(root.val);res.add(temp);}return;}}    }

0 0
原创粉丝点击