LeetCode-Binary Tree Maximum Path Sum
2014-08-28 15:23
357 查看
作者:disappearedgod
文章出处:/article/3730191.html
时间:2014-8-28
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,
Return
Solution(持续更新,java>c++)
文章出处:/article/3730191.html
时间:2014-8-28
题目
Binary Tree Maximum Path Sum
Total Accepted: 17148 TotalSubmissions: 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 |
返回
LeetCodeSolution(持续更新,java>c++)
相关文章推荐
- LeetCode--binary-tree-maximum-path-sum
- Leetcode Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum - LeetCode
- leetcode:Binary Tree Maximum Path Sum
- 【LeetCode with Python】 Binary Tree Maximum Path Sum
- leetcode: Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum 迭代算法
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- [leetcode]Binary Tree Maximum Path Sum
- [leetcode][dfs] Binary Tree Maximum Path Sum
- LeetCode之Binary Tree Maximum Path Sum
- 【leetcode】binary-tree-maximum-path-sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- leetcode[124]Binary Tree Maximum Path Sum
- [Leetcode 124, Hard] Binary Tree Maximum Path Sum