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

Return 6.


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int max;
    public int maxPathSum(TreeNode root) {
        max = Integer.MIN_VALUE;
        sum(root);
        return max;
    }
    /**
     * sum 方法的两个功能
     * 1 计算出以node为根节点能找到的最大值,如果比max大,则max = curValue
     * 2 同时要考虑如果该node作为最后结果(path)的一部分,则要找出 以node 为root 的这棵子树中的最大值,
     *   即 sum 的返回值
     */
    
    private int sum(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int l = sum(node.left);
        int r = sum(node.right);
        int curValue = node.val;
        if (l > 0) {
            curValue += l;
        }
        if (r > 0) {
            curValue += r;
        }
        if (curValue > max) {
            max = curValue;
        }
        //如果左右都为负数,则直接从node 往上找
        return Math.max(Math.max(l,r) + node.val, node.val);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值