Prompt
Branch Sums
Write a function that takes in a Binary Tree and returns a list of its branch sums ordered from leftmost branch sum to rightmost branch sum. A branch sum is the sum of all values in a Binary Tree branch. A Binary Tree branch is a path of nodes in a tree that starts at the rootnode and ends at any leaf node.
Each BinaryTree node has an integer value , a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null .
Sample Input
Sample Ourput
[15,16,18,10,11]
Solution
import java.util.*;
class Program {
// This is the class of the input root. Do not edit it.
public static class BinaryTree {
int value;
BinaryTree left;
BinaryTree right;
BinaryTree(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
public static List<Integer> branchSums(BinaryTree root) {
List<Integer> sums = new ArrayList<Integer>();
branchSums(root, 0, sums);
return sums;
}
public static void branchSums(BinaryTree root, int upSum, List<Integer> sums) { //A
if (root == null) return;//A //B
int newUpSum = upSum + root.value;
if (root.left == null && root.right == null) {
sums.add(newUpSum);
return;
}
//B
branchSums(root.left, newUpSum, sums);
branchSums(root.right, newUpSum, sums);
}
}
# 1A
return;说明void,所以helper函数要注意
# 1B
这里不用用if分情况,因为base是root == null时return