たとえば、次のバイナリツリーがあると仮定します。合計が等しいバイナリツリー内のすべてのパスを見つけよう
[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]
I^2解決策が出てくるかもしれませんが、そこにはもっと良い解決策がありますか?たぶん、スタックやハッシュテーブルを使うような余分なメモリがあります。
私は4時間かけていくつかの解決策を考え出しましたが、すべての解決策があまりにも醜いまたは混沌となりました。
私のn^2解は比較的簡単です。 1)1つの方法、つまりすべての葉が再帰的に呼び出されるヘルパーがあります。合計でパスが見つかると、結果にそのパスを追加します。 2)ツリー内のすべてのノードに対してこのメソッドを呼び出します(O(n)の*はO(n)= O(N^2))
私のシンプルなソリューション
(これははO(n)をとります)//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]