Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

124. Binary Tree Maximum Path Sum #136

Open
Tcdian opened this issue Apr 29, 2020 · 1 comment
Open

124. Binary Tree Maximum Path Sum #136

Tcdian opened this issue Apr 29, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 29, 2020

124. Binary Tree Maximum Path Sum

给定一个 非空 二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径 至少包含一个节点,且不一定经过根节点。

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
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 29, 2020

Solution ( DFS )

  • JavaScript Solution
/**
 * 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 result = -Infinity;
    findMaxSinglePath(root);
    return result;

    function findMaxSinglePath(root) {
        if (root === null) {
            return 0;
        }
        const leftPath = findMaxSinglePath(root.left);
        const rightPath = findMaxSinglePath(root.right);
        result = Math.max(Math.max(leftPath, 0) + Math.max(rightPath, 0) + root.val, result);
        return Math.max(leftPath, rightPath, 0) + root.val;
    }
};
  • TypeScript Solution
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxPathSum(root: TreeNode | null): number {
    let result = -Infinity;
    findMaxSinglePath(root);
    return result;

    function findMaxSinglePath(root: TreeNode | null): number {
        if (root === null) {
            return 0;
        }
        const leftPath = findMaxSinglePath(root.left);
        const rightPath = findMaxSinglePath(root.right);
        result = Math.max(Math.max(leftPath, 0) + Math.max(rightPath, 0) + root.val, result);
        return Math.max(leftPath, rightPath, 0) + root.val;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant