问题描述:
Given a 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 does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
原问题链接:https://leetcode.com/problems/binary-tree-maximum-path-sum/
问题分析
这个问题一开始比较难找到解决的思路。因为这里要求的路径并不一定是从树的根节点经过的路径。而如果把这个问题更加一般化的话,我们计算从某个节点到叶节点的所有可能最大路径,无非就是递归的计算它的两个子节点的最大路径值,再把它们的值和自身加起来。只是我们最终返回的那个是经过根节点的值,它不一定是最大的。
在这里,突然给了我们一个想法,就是在前面递归的过程中,每次都要比较和计算一个当前节点的最大路径值。而如果在这个时候我们用一个全局的变量保存这个最大值,每次都和这个值比较调整的话,这个问题就可以解决了。
于是我们有如下的代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ 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; } }
从实现的思路来说,这里通过借求经过根节点的所有路径的最大值,在每次递归的过程中比较计算最长的路径。这种方式比较巧妙。