/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private static int max;
public int maxPathSum(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
max=-100000;
dfs(root);
return max;
}
private int dfs(TreeNode node){
if(node==null)return 0;
int local_max=node.val;
//node_max = dfs(node.left,max) > 0
int leftmax = dfs(node.left);
int rightmax = dfs(node.right);
if( leftmax > 0)local_max += leftmax;
if( rightmax > 0)local_max += rightmax;
if(max<local_max) max = local_max;
return node.val+Math.max(Math.max(0, leftmax), rightmax);
}
}
Binary Tree Maximum Path Sum
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.