LeetCode 124 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.

找到二叉树,任意两个节点之间路径最长


思路


1 一看到这类题目,马上想到递归

2 想到递归,就从root,left,right的角度结合题目去考虑。

3 对于root,考虑最长路径

a 只在left这边

b 只在right这边

c 通过root,从left到right

4 从递归的角度,越下面的可以保存到这个root网上走的最大值,同时也需要保存计算到目前的最大值。

5 java 可以用传递数组或者全局变量来在递归的时候保存某个值。


代码


public class Solution {
    public int maxPathSum(TreeNode root) {
        if(root==null){
            return 0;
        }
        int[] max = {Integer.MIN_VALUE};
        useme(root,max);
        return max[0];
    }
    
    public int useme(TreeNode root,int[] max){
        if(root==null){
            return 0;
        }
        int leftmax = useme(root.left,max);
        int rightmax = useme(root.right,max);
        int temp1 = leftmax+ rightmax+root.val;
        int temp2 = Math.max(root.val, Math.max(leftmax, rightmax)+root.val);  
        max[0]=Math.max(Math.max(temp1,temp2),max[0]);
        return temp2;
    }
}


15.4.15
public class Solution {
    public int maxPathSum(TreeNode root) {
        if(root == null){
            return 0;
        }
        int[] max = new int[1];
        max[0]=Integer.MIN_VALUE;
        useme(root,max);
        return max[0];
    }
    
    public int useme(TreeNode root, int[] max){
        if(root == null){
            return 0;
        }
        int leftmax = useme(root.left,max);
        int rightmax = useme(root.right,max);
        if(leftmax<0){
            leftmax =0;
        }
        if(rightmax<0){
            rightmax=0;
        }
        max[0]= (leftmax+rightmax+root.val >max[0] ?leftmax+rightmax+root.val:max[0]);
        return root.val+Math.max(leftmax,rightmax);
    }
}


理清楚 max[0] 放的是什么? 这段区域里面的最大值。

return的是什么? 经过root的最大值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值