码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Binary Tree Maximum Path Sum

时间:2020-05-03 14:27:36      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:tree   tput   his   enc   any   href   some   integer   java   

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

Ref: https://zhuanlan.zhihu.com/p/77863151

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        helper(root);
        return max;
    }
    
    public int helper (TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = Math.max(helper(node.left), 0);
        int right = Math.max(helper(node.right), 0);
        
        max = Math.max(max, node.val + left + right);
        
        return node.val + Math.max(left, right);
    }
}

  

LeetCode - Binary Tree Maximum Path Sum

标签:tree   tput   his   enc   any   href   some   integer   java   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/12821756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!