腾讯五十题 No.28 二叉树中的最大路径和

题目链接

class Solution {

    private int res = Integer.MIN_VALUE; 
    public int maxPathSum(TreeNode root) {
        getMax(root);
        return res;
    }

    private int getMax(TreeNode root){
        if(root == null) return 0;
        int left = Math.max(0,getMax(root.left));//左递归
        int right = Math.max(0,getMax(root.right)); //右递归
        res = Math.max(res,root.val+left+right);//每轮更新res
        return Math.max(left,right) + root.val;//每轮返回左右子树中的最大值与每轮的根节点相加
    }
}

0ms

posted @ 2022-02-08 16:26  蹇爱黄  阅读(37)  评论(0)    收藏  举报