您的位置:首页 > 其它

LeetCode-Binary Tree Maximum Path Sum

2014-08-28 15:23 357 查看
作者:disappearedgod

文章出处:/article/3730191.html
时间:2014-8-28

题目




Binary Tree Maximum Path Sum

Total Accepted: 17148 Total
Submissions: 85815My Submissions

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
.



解法

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
int result = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
Queue<Integer> intQ = new LinkedList<Integer>();
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
if(root == null)
return 0;
if(root.left == null && root.right == null)
return root.val;
q.offer(root);
intQ.offer(root.val);
while(q.isEmpty()){
TreeNode t = q.poll();
int tVal = (int) intQ.poll();
if(t.left!=null){
q.offer(t.left);
intQ.offer(tVal + t.left.val);
}
if(t.right!=null){
q.offer(t.right);
intQ.offer(tVal + t.right.val);
}
if(t.right == null || t.left == null){
map.put(tVal,tVal);
}
}
if(!map.isEmpty()){
result = Integer.valueOf(map.lastKey().toString());
map.remove(result);
}
if(!map.isEmpty())
result += Integer.valueOf(map.lastKey().toString());
return result;

}
}


结果

Map is empty


Submission Result: Wrong Answer

Input:{1,2}
Output:0
Expected:3

返回

LeetCode
Solution(持续更新,java>c++)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: