《leetCode》:Path Sum II

来源:互联网 发布:欢聚时代程序员的工资 编辑:程序博客网 时间:2024/06/05 23:02

题目

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   1return[   [5,4,11,2],   [5,8,4,5]]

思路

首先判断当前结点root是否是叶子节点,如果不是,则将此节点值保存,然后分别在此节点的左右子树中寻找是否存在路径之和满足(sum-root.val);如果是叶子节点,则判断该节点的值是否等于sum,如果等于,则符合要求。

实现代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private List<List<Integer>> res=new ArrayList<List<Integer>>();    public List<List<Integer>> pathSum(TreeNode root, int sum) {        pathSumHelper(new ArrayList<Integer>(),root,sum);        return res;    }    private void pathSumHelper(ArrayList<Integer> arrayList, TreeNode root,            int sum) {        if(root==null){            return ;        }        arrayList.add(root.val);        if(root.left==null&&root.right==null){            if(sum==root.val){//符合条件的则将其加入                res.add(arrayList);            }        }        //如果此节点不是叶子节点,则        pathSumHelper(new ArrayList<Integer>(arrayList),root.left,sum-root.val);        pathSumHelper(new ArrayList<Integer>(arrayList),root.right,sum-root.val);       }}
1 0