【发布时间】:2017-07-31 21:55:27
【问题描述】:
例如,给定以下二叉树:
[2,3,5,4,8,6,-2,null,null,null,null,null,null,null,2] 和 sum = 7
2
/ \
3 5
/ \ / \
4 8 6 -2
\
2
打印:[3,4] , [2,5] , [2,5,-2,2]
我可以想出一个 n^2 的解决方案,但有更好的解决方案吗?也许有一些额外的内存,比如使用堆栈或哈希表。
我花了 4 个小时试图提出一些解决方案,但所有解决方案都变得太丑陋或混乱。
我的 n^2 解决方案比较简单: 1)有一种方法,即递归调用自身直到所有叶子的助手。当它找到带有总和的路径时,将其添加到结果中。 (这将花费 O(n)) 2)为树中的每个节点调用此方法( O(n) * O(n) = O(n^2))
我的简单解决方案
//TreeNode structure
public class TreeNode {
int val;
public TreeNode left;
public TreeNode right;
TreeNode(int x) { val = x; }
}
//Solution class
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while ( !q.isEmpty())
{
TreeNode top = q.poll();
helper(top,sum,temp,result);
if (top.left != null) q.offer(top.left);
if (top.right != null) q.offer(top.right);
}
return result;
}
public void helper(TreeNode root, int sum, List<Integer> temp, List<List<Integer>> result)
{
if (root == null) return;
temp.add(root.val) ;
if (root.val == sum)
{
result.add(new ArrayList<>(temp));
}
helper(root.left,sum-root.val, temp, result );
helper(root.right, sum-root.val, temp, result);
temp.remove(temp.size() - 1);
}
}
//Execution class
public class treeApp {
public static void main(String args[])
{ TreeNode root = new TreeNode(2);
root.left = new TreeNode(3);
root.right = new TreeNode(5);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(-2);
root.right.right.right = new TreeNode(2);
Solution sol = new Solution();
List<List<Integer>> result ;
result = sol.pathSum(root, 7);
for (List l : result)
{
System.out.println(l.toString());
}
}
//Prints:
[2, 5]
[2, 5, -2, 2]
[3, 4]
【问题讨论】:
标签: algorithm recursion optimization time-complexity binary-tree