LeetCode - Path Sum II
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] ]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> resList = new ArrayList<List<Integer>>(); if (root == null) { return resList; } List<Integer> aList = new ArrayList<Integer>(); aList.add(root.val); helper(root, resList, aList, root.val, sum); return resList; } public void helper (TreeNode node, List<List<Integer>> resList, List<Integer> aList, int currentSum, int sum) { if (node.left == null && node.right == null){ if (currentSum == sum) { resList.add(aList); } return; } if (node.left != null){ List<Integer> leftList = new ArrayList<>(aList); leftList.add(node.left.val); helper(node.left, resList, leftList, currentSum+node.left.val, sum); } if (node.right != null){ List<Integer> rightList = new ArrayList<>(aList); rightList.add(node.right.val); helper(node.right, resList, rightList, currentSum+node.right.val, sum); } return; } }
posted on 2020-04-13 12:43 IncredibleThings 阅读(173) 评论(0) 编辑 收藏 举报