zoukankan      html  css  js  c++  java
  • 124. Binary Tree Maximum Path Sum(js)

    124. 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
    题意:求二叉树最大路径和
    代码如下:
    /*
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var maxPathSum = function(root) {
        let res=-Infinity;
        function sum(root){
            if(!root) return 0;
            let left=sum(root.left);
            let right=sum(root.right);
            if(left>0 && right>0){
                res=Math.max(res,left+right+root.val);
            }else if(left>0){
                res=Math.max(res,left+root.val);
            }else if(right>0){
                res=Math.max(res,right+root.val);
            }else{
                res=Math.max(res,root.val);
            }
            return Math.max(root.val,root.val+Math.max(left,right));
        }
        sum(root);
        return res;
    }
  • 相关阅读:
    找零钱「Usaco2006 Dec」
    才艺表演「Usaco2018 Open」
    潜入行动「JSOI2018」
    任务安排「SDOI2012」
    BZOJ2298: [HAOI2011]problem a
    JZOJ 5818
    JZOJ 3493
    JZOJ 3470
    JZOJ 5781
    JZOJ 5778
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10864361.html
Copyright © 2011-2022 走看看