题目地址:链接
思路: 每次返回当前路径(包含当前节点,左右分支中的最大值),并判断当前路径是否超过当前记录的最大值。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
let ans = root.val;
let dfs = (root) => {
if(!root) return 0;
let left = dfs(root.left);
let right= dfs(root.right);
let rootans = Math.max(left, right, 0) + root.val;
ans = Math.max(Math.max(left, 0) + Math.max(right, 0) + root.val, ans);
return Math.max(rootans, 0);
}
dfs(root);
return ans;
};

被折叠的 条评论
为什么被折叠?



