Path Sum II

来源:互联网 发布:mac os x 10.12.6镜像 编辑:程序博客网 时间:2024/06/16 09:08
Problem:

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   1

return

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


Solution:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
int gsum;
 public List<List<Integer>> pathSum(TreeNode root, int sum) {
     if(root==null)
         return result;
         gsum = sum;
         subSum(root, 0);
         return result;
    }
    
    private void subSum(TreeNode root, int preSum)
    {
         if(root.left!=null)
         {
             list.add(root.val);
             subSum(root.left, preSum+root.val);
             list.remove(list.size()-1);
         }
         if(root.right!=null)
         {
             list.add(root.val);
             subSum(root.right, preSum+root.val);
             list.remove(list.size()-1);
         }
         if(root.left==null&&root.right==null)
         {
             if(preSum+root.val==gsum)
             {
                 ArrayList<Integer> ls = new ArrayList<>(list);
                 ls.add(root.val);
                 result.add(ls);
             }
         }
    }
}
0 0
原创粉丝点击