zoukankan      html  css  js  c++  java
  • 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:

  • 相关阅读:
    解决SecureCRT中文显示乱码
    Linux命令: chown
    secureCRT登录不上ubuntu,Connection closed
    another app is currently holding the yum lock;waiting for it to exit解决
    分析一个socket通信: server/client
    Centos配置国内yum源
    liteos CPU占用率(十六)
    ft6236 触摸屏驱动
    Multi-touch (MT) Protocol 小结
    liteos 异常接管(十五)
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7465510.html
Copyright © 2011-2022 走看看