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;
    }
  • 相关阅读:
    Kettle学习(2)
    kettle学习(1)
    Quartz在Spring中的使用
    JVM垃圾收集简介
    快速排序

    20190827最新论文
    GNN
    Multimodal Machine Learning
    Wasserstein距离 及两多元高斯分布间的W距离
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10864361.html
Copyright © 2011-2022 走看看