题解 | #二叉树中的最大路径和#
二叉树中的最大路径和
http://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
int maxSum=Integer.MIN_VALUE;//初始化为系统最小
//该函数的含义为返回以root为根节点且以root为起点的最大路径和大小
public int process(TreeNode root){
if(root==null)
return 0;
int leftData=Math.max(process(root.left),0);
int rightData=Math.max(process(root.right),0);
maxSum=Math.max(maxSum,root.val+leftData+rightData);
return root.val+Math.max(leftData,rightData);
}
public int maxPathSum (TreeNode root) {
// write code here
process(root);
return maxSum;
}
}
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
int maxSum=Integer.MIN_VALUE;//初始化为系统最小
//该函数的含义为返回以root为根节点且以root为起点的最大路径和大小
public int process(TreeNode root){
if(root==null)
return 0;
int leftData=Math.max(process(root.left),0);
int rightData=Math.max(process(root.right),0);
maxSum=Math.max(maxSum,root.val+leftData+rightData);
return root.val+Math.max(leftData,rightData);
}
public int maxPathSum (TreeNode root) {
// write code here
process(root);
return maxSum;
}
}