Skip to content

Latest commit

 

History

History
79 lines (53 loc) · 1.89 KB

File metadata and controls

79 lines (53 loc) · 1.89 KB

124. Binary Tree Maximum Path Sum - 二叉树中的最大路径和

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

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

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

题目标签:Tree / Depth-first Search

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
java 1 ms 40.7 MB
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int ret = Integer.MIN_VALUE;

    private int findBest(TreeNode root) {
        if (root == null)
            return 0;
        
        int left = Math.max(0, findBest(root.left));
        int right = Math.max(0, findBest(root.right));

        int sum = root.val + left + right;
        ret = Math.max(ret, sum);

        return root.val + Math.max(left, right);
    }

    public int maxPathSum(TreeNode root) {
        findBest(root);
        return ret;
    }
}