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: recursion
跟Path Sum的要求很接近,寻找从根到叶子的路径。要求是求所有满足条件的路径,所以需要数据结构来维护中间路径结果以及保存满足条件的所有路径。
这里的时间是一次遍历O(n),而空间复杂度则取决于满足条件的路径和的数量(假设是k条),则空间是O(klogn)。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList> pathSum(TreeNode root, int sum) { ArrayList > res = new ArrayList >(); if(root == null) return res; ArrayList item = new ArrayList (); item.add(root.val); helper(root, sum - root.val, item, res); return res; } public void helper(TreeNode root, int sum, ArrayList item, ArrayList > res) { if(root == null) return; if(root.left == null && root.right == null && sum == 0) { res.add(new ArrayList (item)); return; } if(root.left != null) { item.add(root.left.val); helper(root.left, sum - root.left.val, item, res); item.remove(item.size() - 1); } if(root.right != null) { item.add(root.right.val); helper(root.right, sum - root.right.val, item, res); item.remove(item.size() - 1); } } }
No comments:
Post a Comment