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; }