113-Path Sum II

kevin聰發表於2018-05-25

Description

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

Note: A leaf is a node with no children.


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

問題描述

給定二叉樹和sum, 找出所有根節點到葉子節點的路徑, 這些路徑上的所有節點之和等於sum


問題分析


解法

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList();
        if(root == null) return res;

        findPath(root, res, new ArrayList(), sum);

        return res;
    }
    public void findPath(TreeNode root, List<List<Integer>> res, List<Integer> line, int sum){
        line.add(root.val);
        sum -= root.val;
        if(root.left == null && root.right == null && sum == 0) res.add(new ArrayList(line));
        if(root.left != null) findPath(root.left, res, line, sum);
        if(root.right != null) findPath(root.right, res, line, sum);
        line.remove(line.size() - 1);
    }   
}