Binary Tree Maximum Path Sum(LeetCode)

题目:

难度级别: ★★★

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

Return 6.

题目分析:题目要求在一个二叉树中,找出一条路径能经过的最大和。这条路径可以以二叉树中任何一个节点为起点和终点。


思路:

暂略


代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    static int max;
    public int maxPathSum(TreeNode root) {
        if (root == null){
            return 0;
        }
        max = root.val;
        getPathSum(root);
        return max;
    }
    
    static int getPathSum(TreeNode root){
        if (root == null){
            return 0;
        }
        int lsum,rsum;
        int sum = root.val;
        lsum = getPathSum(root.left);
        rsum = getPathSum(root.right);
        //find the max sum from left child to right child via root, compare the result with max
        if (lsum > 0){
            sum += lsum;
        }
        if (rsum > 0){
            sum += rsum;
        }
        if (sum > max){
            max = sum;
        }
        //choose either or neither of rsum and lsum, plus root.val as the result to return to the up level
        if (rsum > 0 && rsum >= lsum){
            return rsum + root.val;
        }else if (lsum > 0 && lsum >= rsum){
            return lsum + root.val;
        }
        return root.val;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值