Instructions:
Fun with trees: max sumhtml
Solution:
//https://www.codewars.com/kata/57e5279b7cf1aea5cf000359/train/java
import java.util.ArrayList;
class Solution{
static int maxSum(TreeNode root){
ArrayList<ArrayList<Integer>> allPaths = new FindShortestBTPath().findAllPath(root);
int max = 0;
for(ArrayList<Integer> path: paths){
int sum = 0;
for(Integer x : path){
sum += x;
}
if(sum > max){
max = sum;
}
}
return max;
}
private static class FindShortestBTPath{
private ArrayList<ArrayList<Integer>> allPaths = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> onePath = ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> findAllPath(TreeNode root){
if(root == null){
return allPaths;
}
onePath.add(root.value);
if(root.left == null && root.right == null){
allPaths.add(newArrayList<Integer>(onePath));
}
findAllPath(root.left);
findAllPath(root.right);
onePath.remove(onePath.size() - 1);
return allPaths;
}
}
}
Example Test:
https://www.codewars.com/kata/57e5279b7cf1aea5cf000359/train/java
Reference
二叉樹中全部的路徑(從根節點到葉子結點)java