LeetCode - Binary Tree Maximum Path Sum
2013-04-23 18:10
351 查看
递归加记忆化搜索,PASS Large Judge
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { Map<TreeNode, Integer> map1 = new HashMap<TreeNode, Integer>(); Map<TreeNode, Integer> map2 = new HashMap<TreeNode, Integer>(); public int maxPathSum(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function if (root == null) return 0; if (map1.get(root) != null) return map1.get(root); int value = root.val; int sonLeft = max(root.left); int sonRight = max(root.right); if (sonLeft>0) value += sonLeft; if (sonRight>0) value += sonRight; if (root.left != null) { value = Math.max(value, maxPathSum(root.left)); } if (root.right != null) { value = Math.max(value, maxPathSum(root.right)); } map1.put(root, value); return value; } public int max(TreeNode node) { if (node == null) return 0; if (map2.get(node) != null) return map2.get(node); int value = node.val; int son = Math.max(max(node.left), max(node.right)); if (son>0) value += son; map2.put(node, value); return value; } }
相关文章推荐
- leetcode: Binary Tree Maximum Path Sum
- LeetCode 124 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
- leetcode Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum 迭代算法
- leetcode 124: Binary Tree Maximum Path Sum
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- 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[124]Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum