【多次过】Lintcode 246. 二叉树的路径和 II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/86685313

给一棵二叉树和一个目标值,设计一个算法找到二叉树上的和为该目标值的所有路径。路径可以从任何节点出发和结束,但是需要是一条一直往下走的路线。也就是说,路径上的节点的层级是逐个递增的。

样例

对于二叉树:

    1
   / \
  2   3
 /   /
4   2

给定目标值6。那么满足条件的路径有两条:

[
  [2, 4],
  [1, 3, 2]
]

解题思路:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: the root of binary tree
     * @param target: An integer
     * @return: all valid paths
     */
    public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) return list;
        
        helper(root, target, list, new ArrayList<Integer>());
        
        return list;
    }
    
    private void helper(TreeNode root, int target, List<List<Integer>> list, List<Integer> path) {
        if (root == null) return;
        
        int sum = 0;
        path.add(Integer.valueOf(root.val));
        
        for (int i = path.size() - 1; i >= 0; i--) {
            sum += path.get(i);
            
            if (sum == target) 
                list.add(new ArrayList<Integer>(path.subList(i, path.size())));
        }
        
        if (root.left != null) 
            helper(root.left, target, list, path);
        if (root.right != null)
            helper(root.right, target, list, path);

        path.remove(path.size() - 1);
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/86685313