树——binary-tree-maximum-path-sum(二叉树最大路径和)

问题

  Given a binary tree, find the maximum path sum.

  The path may start and end at any node in the tree.

  For example:
  Given the below binary tree,

         1
        / 
       2   3 

  Return6.

思路

  用递归方法从叶节点开始,将所求最大路径和maxValue设为全局变量,并赋初始值。

  假设递归到节点n,首先计算左子树的最大路径和left,并与0进行比较,若left<0,则left=0。同理求出右子树最大路径和right。

  将maxValue与left+right+root.val比较,把较大值赋于maxValue。

  递归函数的函数值为节点n.val与左右子树中较大值的和

代码

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int maxValue = Integer.MIN_VALUE;
12     
13     public int maxPathSum(TreeNode root) {
14         if(root==null)
15             return 0;
16         max(root);
17         return maxValue;
18     }
19     public int max(TreeNode root){
20         if(root==null)
21             return 0;
22         int left = Math.max(0, max(root.left));
23         int right = Math.max(0, max(root.right));
24         maxValue = Math.max(maxValue, left+right+root.val);
25         return Math.max(left, right)+root.val;
26     }
27 }
原文地址:https://www.cnblogs.com/jiqianqian/p/7389467.html