94题 Binary Tree Maximum Path Sum

该博客主要讨论如何解决一个计算机科学问题,即在给定的二叉树中找到最大的路径和。路径可以始于和终止于树中的任意节点,路径和是路径上所有节点值的总和。解决方案通过递归地遍历每个节点来计算左子树和右子树的最大路径,并更新全局最大路径和。关键在于理解如何有效地计算节点的最大贡献并处理负数的情况。

Binary Tree Maximum Path Sum

Description
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
(Path sum is the sum of the weights of nodes on the path between two nodes.)

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    //private TreeNode subTree = null ;
    
    private int maxSum;
    
    public int maxPathSum(TreeNode root) {
        maxSum = Integer.MIN_VALUE;
        findMax(root);
        return maxSum;
    }
    
    private int findMax(TreeNode node) {
        if (node == null) return 0;

        int left = findMax(node.left);
        int right = findMax(node.right); 

        maxSum = Math.max(node.val + left + right, maxSum);
        int path = node.val + Math.max(left, right);
        return Math.max(path, 0); //当某一端为负时,返回0.
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值