Branch Sums

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值