Max Path Sum In Binary Tree

Prompt

Write a function that takes in a Binary Tree and returns its max path sum. A path is a collection of connected nodes in a tree where no node is connected to more than two other nodes; a path sum is the sum of the values of the nodes in a particular path.
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 Output

10

Solution

import java.util.*;

class Program {
  public static int maxPathSum(BinaryTree tree) {
		List<Integer> maxSumArray = findMaxSum(tree);// A
    return maxSumArray.get(1);// B
  }
	
	public static List<Integer> findMaxSum(BinaryTree tree) {
		if (tree == null) {
			return new ArrayList<Integer> (Arrays.asList(0, Integer.MIN_VALUE));
		}
		List<Integer> leftMaxSumArray = findMaxSum(tree.left);
		Integer leftMaxSumAsBranch = leftMaxSumArray.get(0);
		Integer leftMaxPathSum = leftMaxSumArray.get(1);
		
		List<Integer> rightMaxSumArray = findMaxSum(tree.right);
		Integer rightMaxSumAsBranch = rightMaxSumArray.get(0);
		Integer rightMaxPathSum = rightMaxSumArray.get(1);
		
		Integer maxChildSumAsBranch = Math.max(leftMaxSumAsBranch, rightMaxSumAsBranch);
		Integer maxSumAsBranch = Math.max(maxChildSumAsBranch + tree.value, tree.value);
		Integer maxSumAsRootNode =
			Math.max(leftMaxSumAsBranch + tree.value + rightMaxSumAsBranch,maxSumAsBranch);
		int maxPathSum = Math.max(maxSumAsRootNode, Math.max(leftMaxPathSum, rightMaxPathSum)); // C
		return new ArrayList<Integer> (Arrays.asList(maxSumAsBranch, maxPathSum));
	}

  static class BinaryTree {
    public int value;
    public BinaryTree left;
    public BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
    }
  }
}

# A

当需要两个返回值的时

# B

  • the methond of int [ ] & List

# C

Math.max( ) 只可以比较两个值的大小

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值