113. Path Sum II

Description

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,

113. Path Sum II_第1张图片
tree

return

[
[5,4,11,2],
[5,8,4,5]
]

Solution

DFS

在leaf节点处就要停止递归了哦。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> pathSum(TreeNode root, int sum) {
        List> paths = new LinkedList<>();
        pathSumRecur(root, sum, new LinkedList<>(), paths);
        return paths;
    }
    
    public void pathSumRecur(TreeNode root, int sum
                             , List path, List> paths) {
        if (root == null) {            
            return;
        }
        
        path.add(root.val);
        
        if (root.left == null && root.right == null) {
            if (root.val == sum) {
                paths.add(new LinkedList<>(path));
            }
        } else {
            pathSumRecur(root.left, sum - root.val, path, paths);
            pathSumRecur(root.right, sum - root.val, path, paths);    
        }
        
        path.remove(path.size() - 1);
    }
}

你可能感兴趣的:(113. Path Sum II)