Binary Tree Maximum Path Sum

来源:互联网 发布:闪电抢购软件下载 编辑:程序博客网 时间:2024/04/28 15:45

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

第91个case过不了:

90 / 92 test cases passed.
Status: 

Wrong Answer

 
Submitted: 0 minutes ago
Input:{9,6,-3,#,#,-6,2,#,#,2,#,-6,-6,-6}Output:15Expected:16

但我把那个test case本地构建出来,返回的结果是正确的啊,我的程序的确返回了16。不知道为什么。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private int res;public int maxPathSum(TreeNode root) {if (root == null) {return 0;}        res = Integer.MIN_VALUE;        longestPath(root);        return res;    }private int longestPath(TreeNode node){if (node == null) {return 0;}int left = longestPath(node.left);int right = longestPath(node.right);if (left < 0 && right < 0) {res = Math.max(res, node.val);}res = Math.max(left + right + node.val, res);if (left > right) {res = Math.max(left + node.val, res);return left + node.val;}else{res = Math.max(right + node.val, res);return right + node.val;}}}


0 0
原创粉丝点击