• leetcode--124. Binary Tree Maximum Path Sum


    1、问题描述

    Given a binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3

    Return 6.

    2、边界条件:无

    3、思路:最大路径值,一个单向路径的最大值已经解决了,一个节点向下的左右两条路径。这道题目可以跨一个节点的两个子节点。这里需要多考虑一个路径,就是左右路径和该节点组成的长路径。另外一点需要注意,一条路径如果<0 ,则可以不连接。需要一个变量来传递当前的最大路径值。

    4、代码实现

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxPathSum(TreeNode root) {
            int[] maxVal = new int[1];
            maxVal[0] = Integer.MIN_VALUE;
            maxPathSum(root, maxVal);
            return maxVal[0];
        }
    
        public int maxPathSum(TreeNode root, int[] maxVal) {
            if (root == null) {
                return 0;
            }
            int leftMaxVal = Math.max(0, maxPathSum(root.left, maxVal));
            int rightMaxVal = Math.max(0, maxPathSum(root.right, maxVal));
            maxVal[0] = Math.max(maxVal[0], leftMaxVal + rightMaxVal + root.val);
            return Math.max(leftMaxVal, rightMaxVal) + root.val;
        }
    }

    5、时间复杂度:O(N), 空间复杂度:

    6.api:

  • 相关阅读:
    Java List集合
    Java 集合删除重复元素、删除指定元素
    进程和线程
    Java 线程的同步与死锁
    Java 线程的常用操作方法
    Java 多线程实现
    统计分析
    递归方法(回文)
    素数的输出
    动手动脑二
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7465510.html
Copyright © 2020-2023  润新知