Binary Tree Path Sum II

Your are given a binary tree in which each node contains a value. Design an algorithm to get all paths which sum to a given value. The path does not need to start or end at the root or a leaf, but it must go in a straight line down.

Example

Example 1:

Input:
{1,2,3,4,#,2}
6
Output:
[[2, 4],[1, 3, 2]]
Explanation:
The binary tree is like this:
    1
   / \
  2   3
 /   /
4   2
for target 6, it is obvious 2 + 4 = 6 and 1 + 3 + 2 = 6.

Example 2:

Input:
{1,2,3,4}
10
Output:
[]
Explanation:
The binary tree is like this:
    1
   / \
  2   3
 /   
4   
for target 10, there is no way to reach it.

思路:作为I的扩展,起点和终点不在固定,那么preorder的妙处就在于:每次从当前node的value往前sum,看谁能够sum成target,然后取list的sublist到result中。

/**
 * 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>> lists = new ArrayList<List<Integer>>();
        if(root == null) {
            return lists;
        }
        List<Integer> list = new ArrayList<Integer>();
        list.add(root.val);
        dfs(root, lists, list, target);
        return lists;
    }
    
    private void dfs(TreeNode node, List<List<Integer>> lists, List<Integer> list, int target) {
        if(node == null) {
            return;
        }
        
        //这题精妙之处,在于收集了node之后,可以取sublist;
        //每次从当前node往前数,看谁能够sum成target;
        int sum = 0;
        for(int i = list.size() -1; i >= 0; i--) {
            sum += list.get(i);
            if(sum == target){
                lists.add(new ArrayList<Integer>(list.subList(i, list.size())));
            }
        }
        
        if(node.left != null) {
            list.add(node.left.val);
            dfs(node.left, lists, list, target);
            list.remove(list.size() - 1);
        }

        if(node.right != null) {
            list.add(node.right.val);
            dfs(node.right, lists, list, target);
            list.remove(list.size() -1);
        }
    }
}
发布了562 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/103698352