Binary Tree Maximum Path Sum
Posted hygeia
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Tree Maximum Path Sum相关的知识,希望对你有一定的参考价值。
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3] 1 / 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / 9 20 / 15 7 Output: 42
解题思路
- A path from start to end, goes up on the tree for 0 or more steps, then goes down for 0 or more steps. Once i
public class Solution { int maxValue; public int maxPathSum(TreeNode root) { maxValue = Integer.MIN_VALUE; maxPathDown(root); return maxValue; } private int maxPathDown(TreeNode node) { if (node == null) return 0; int left = Math.max(0, maxPathDown(node.left)); int right = Math.max(0, maxPathDown(node.right)); maxValue = Math.max(maxValue, left + right + node.val); return Math.max(left, right) + node.val; } }
- A recursive method
maxPathDown(TreeNode node)
(1) computes the maximum path sum with highest node is the input node, update maximum if necessary (2) returns the maximum sum of the path that can be extended to input node‘s parent.
以上是关于Binary Tree Maximum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章
124. Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum(mock)
LeetCode - Binary Tree Maximum Path Sum