递归-LeetCode124-二叉树中的最大路径和

题目

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6
示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

思路

设某节点的值a,其左子节点方向所能提供的路径最大值b,其右子节点方向所能提供的路径最大值c。

所求结果为 a,a+b,a+c,b+a+c中的最大值。

代码

/**
 * 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) {
        path(root);
        return max;
    }
    
    public int path(TreeNode root){
        int mid=root.val;
        // 无左右子节点的情况、只有右子节点的情况、只有左子节点的情况、有左右子节点的情况
        // 维护两个变量。一个是随时更新的全局最大路径变量 max ,一个是当前节点所能提供的路径最大值 pathmax。
        if(root.left==null && root.right==null){
            max=Math.max(max,mid);
            int pathmax=mid;
            return pathmax;
        }else
        if(root.left==null && root.right!=null){
            int pathmax=mid;
            int r=path(root.right);
            if(mid+r>pathmax){
                pathmax=mid+r;
            }
            max=Math.max(max,pathmax);
            return pathmax;
        }else
        if(root.left!=null && root.right==null){
            int pathmax=mid;
            int l=path(root.left);
            if(mid+l>pathmax){
                pathmax=mid+l;
            }
            max=Math.max(max,pathmax);
            return pathmax;
        }else
        {
            int pathmax=mid;
            int l=path(root.left);
            int r=path(root.right);
            if(mid+l>pathmax){
                pathmax=mid+l;
            }
            if(mid+r>pathmax){
                pathmax=mid+r;
            }
            max=Math.max(max,pathmax);
            max=Math.max(max,l+r+mid);
            return pathmax;
        }
        
    }
    
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值