Leetcode刷题java之124. 二叉树中的最大路径和(一天一道编程题之五十二天)

执行结果:

通过

显示详情

执行用时 :1 ms, 在所有 Java 提交中击败了99.80% 的用户

内存消耗 :41.5 MB, 在所有 Java 提交中击败了15.00%的用户

题目:

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

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

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6


示例 2:

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

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

深度遍历,具体见代码。

代码:

/**
 * 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) {
        if(root==null)
        {
            return 0;
        }
        dfs(root);
        return max;
    }
    public int dfs(TreeNode root)
    {
        if(root==null)
        {
            return 0;
        }
        //左边如果为负还不如没有
        int leftMax=Math.max(0,dfs(root.left));
        //右边如果为负还不如没有
        int rightMax=Math.max(0,dfs(root.right));
        //不断更新最大值
        max=Math.max(max,root.val+leftMax+rightMax);
        //如果往上返回的话,左右只能一条路
        return root.val+Math.max(leftMax,rightMax);
    }
}

 

你可能感兴趣的:(java面经之查缺补漏,Leecode,二叉树)