华为2021届机试题二叉树路径最大和

建树的地方有一点问题,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));
  }

 }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值