Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum.
Anonymous
public List> pathSum(TreeNode root, int targeSum) { return dfs(root, targeSum, new ArrayList()); } private List> dfs(TreeNode root, int targeSum, List list) { List> result = new ArrayList(); if(root==null) { return result; } if(root.left == null && root.right == null && targeSum - root.val == 0) { list.add(root.val); result.add(new ArrayList(list)); list.remove(list.size()-1); } list.add(root.val); dfs(root.left, targeSum - root.val, list); dfs(root.right, targeSum - root.val, list); list.remove(list.size()-1); return result; }
Check out your Company Bowl for anonymous work chats.