您的位置:首页 > 其它

LeetCode - Binary Tree Maximum Path Sum

2013-04-23 18:10 295 查看
递归加记忆化搜索,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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: