建树的地方有一点问题,0也是结点了,但应该不影响结果
import java.util.*;
class TreeNode{
int val;
TreeNode left = null;
TreeNode right = null;
TreeNode(int x){
val = x;
}
}
public class Main {
public static int res = Integer.MIN_VALUE;
private static int maxSum(TreeNode root) {
if(null == root) {
return 0;
}
int l_max = Math.max(maxSum(root.left), 0);
int r_max = Math.max(maxSum(root.right), 0);
res = Math.max(res, l_max + r_max + root.val);
return root.val + Math.max(l_max, r_max);
}
public static int maxPathSum(TreeNode root) {
maxSum(root);
return res;
}
public static TreeNode str2tree(String s) {
if(s == null || s.length() == 0){
return null;
}
Stack<TreeNode> stk = new Stack<TreeNode>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c>='0' && c<='9' || c=='-'){
int start = i;
while(i+1<s.length() && s.charAt(i+1)>='0' && s.charAt(i+1)<='9'){
i++;
}
TreeNode cur = new TreeNode(Integer.valueOf(s.substring(start, i+1)));
if(!stk.isEmpty()){
TreeNode top = stk.peek();
if(top.left == null){
top.left = cur;
}else{
top.right = cur;
}
}
stk.push(cur);
}else if(c == ')'|| c == ','){
stk.pop();
}
}
return stk.peek();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String str = in.next();
if(str.length()== 0){
System.out.println(0);
}
TreeNode root = str2tree(str);
System.out.println(maxPathSum(root));
}
}
}