Binary Tree Path Sum Lintcode
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target
.
A valid path is from root node to any of the leaf nodes.
Example
Given a binary tree, and target = 5
:
1
/ \
2 4
/ \
2 3
return
[
[1, 2, 2],
[1, 4]
]
这道题居然一遍bug free了。。。但好像空间复杂度有点高。。。
public class Solution { /** * @param root the root of binary tree * @param target an integer * @return all valid paths */ public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { List<List<Integer>> res = new ArrayList<>(); helper(root, target, res, new ArrayList<Integer>()); return res; } public TreeNode helper(TreeNode root, int target, List<List<Integer>> res, List<Integer> sub) { if (root == null) { return null; } sub.add(root.val); TreeNode left = helper(root.left, target - root.val, res, new ArrayList<>(sub)); TreeNode right = helper(root.right, target - root.val, res, new ArrayList<>(sub)); if (left == null && right == null && target - root.val == 0) { res.add(sub); } return root; } }
看了下答案,原来还可以改进一下,每次回去的时候把添加的值去掉,这样就不用不停地建新的了。对递归的认识好像又深了一点呢。
public class Solution { /** * @param root the root of binary tree * @param target an integer * @return all valid paths */ public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { List<List<Integer>> res = new ArrayList<>(); helper(root, target, res, new ArrayList<Integer>()); return res; } public void helper(TreeNode root, int target, List<List<Integer>> res, List<Integer> sub) { if (root == null) { return; } sub.add(root.val); if (root.left == null && root.right == null && target - root.val == 0) { res.add(new ArrayList<>(sub)); return; } helper(root.left, target - root.val, res, sub); if (root.left != null) { sub.remove(sub.size() - 1); } helper(root.right, target - root.val, res, sub); if (root.right != null) { sub.remove(sub.size() - 1); } } }
今天又做了一遍这道题,虽然思路还是会的但是居然写最优解还是卡住了!心酸啊,要注意只要递归的不是null就说明这个点被加过了所以要remove掉。如果是null的话就没有被加过,就不要平白无故的remove了。
另外这道题居然也可以用linkedlist和stack来解,也可以返回linkedlist。思路差不多,在此不表。
还是回顾一下吧。。。心酸。。。