例如,給定以下二叉樹:查找二叉樹中所有等於總和的路徑
[2,3,5,4,8,6,-2,null,null,null, NULL,NULL,NULL,NULL,2]和總和= 7
2
/ \
3 5
/ \ / \
4 8 6 -2
\
2
打印:[3,4],[2,5],[2,5,-2,2]
我可以拿出一個^ 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]