LeetCode之二叉树中的最大路径和

1. 题目描述

https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/

2. 示例代码

递归是真的好用

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int max  = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root)
    {
        if(root == null)
            return 0;

        slove(root);

        return max;
    }

    private int slove(TreeNode root)
    {
        if(root == null)
            return 0;

        int val = root.val;
        int leftMax = slove(root.left);
        int rightMax = slove(root.right);

        int temp = val + Math.max(0,leftMax) + Math.max(0,rightMax);
        max = Math.max(max,temp);

        return val + Math.max(Math.max(0,leftMax),Math.max(0,rightMax));
    }
}
发布了306 篇原创文章 · 获赞 46 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/kaikai_sk/article/details/92794968