leetcode: Binary Tree Maximum Path Sum

159 篇文章 0 订阅

问题描述:

Given a 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 does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

 

Return 6.

原问题链接:https://leetcode.com/problems/binary-tree-maximum-path-sum/

 

问题分析

  这个问题一开始比较难找到解决的思路。因为这里要求的路径并不一定是从树的根节点经过的路径。而如果把这个问题更加一般化的话,我们计算从某个节点到叶节点的所有可能最大路径,无非就是递归的计算它的两个子节点的最大路径值,再把它们的值和自身加起来。只是我们最终返回的那个是经过根节点的值,它不一定是最大的。

  在这里,突然给了我们一个想法,就是在前面递归的过程中,每次都要比较和计算一个当前节点的最大路径值。而如果在这个时候我们用一个全局的变量保存这个最大值,每次都和这个值比较调整的话,这个问题就可以解决了。

  于是我们有如下的代码:

 

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

  从实现的思路来说,这里通过借求经过根节点的所有路径的最大值,在每次递归的过程中比较计算最长的路径。这种方式比较巧妙。 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值