zoukankan      html  css  js  c++  java
  • Binary Tree Maximum Path Sum

    Given a non-empty 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.

    Example 1:

    Input: [1,2,3]
    
           1
          / 
         2   3
    
    Output: 6
    

    Example 2:

    Input: [-10,9,20,null,null,15,7]
    
       -10
       / 
      9  20
        /  
       15   7
    
    Output: 42


    解题思路
    • A path from start to end, goes up on the tree for 0 or more steps, then goes down for 0 or more steps. Once i
      public class Solution {
          int maxValue;
          
          public int maxPathSum(TreeNode root) {
              maxValue = Integer.MIN_VALUE;
              maxPathDown(root);
              return maxValue;
          }
          
          private int maxPathDown(TreeNode node) {
              if (node == null) return 0;
              int left = Math.max(0, maxPathDown(node.left));
              int right = Math.max(0, maxPathDown(node.right));
              maxValue = Math.max(maxValue, left + right + node.val);
              return Math.max(left, right) + node.val;
          }
      }
      t goes down, it can't go up. Each path has a highest node, which is also the lowest common ancestor of all other nodes on the path.
    • A recursive method maxPathDown(TreeNode node) (1) computes the maximum path sum with highest node is the input node, update maximum if necessary (2) returns the maximum sum of the path that can be extended to input node's parent.
  • 相关阅读:
    (九)MySQL用户和权限管理
    activemq修改admin密码
    zookeeper与activemq整合
    (十一)数组array
    (十)while和until循环
    (八)MySQL索引操作
    查看MySQL是否在运行
    MySQL的启动和关闭
    常用的Web服务器软件整理
    [CodeForce 801A] Vicious Keyboard
  • 原文地址:https://www.cnblogs.com/hygeia/p/10052229.html
Copyright © 2011-2022 走看看