zoukankan      html  css  js  c++  java
  • LeetCode 124

    https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/

    这个题明明有思路,但是写出来的代码就是一团糟还过不了,一气之下直接放弃治疗看讨论区了。。

    先贴代码

    class Solution {
        int realMax = Integer.MIN_VALUE;
        public int maxPathSum(TreeNode root) {
           getMax(root);
           return realMax;
        }
        private int getMax(TreeNode root){
            if(root == null){
                return 0;
            }
            int left = Math.max(0,getMax(root.left));
            int right = Math.max(0,getMax(root.right));
            realMax = Math.max(realMax, root.val+left+right);
            return Math.max(left, right) + root.val;
        }
    }
    View Code

    https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/comments/3015

    哈,今天是2020年6月21日,这个题作为今天的每日一题出现了,两个月前的我鸡的一批,一个月前做要WA6次,这次WA1次就过了,希望自己继续努力!

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int max = Integer.MIN_VALUE;
        public int maxPathSum(TreeNode root) {
            int temp = helper(root);
            return max;
        }
    
        private int helper(TreeNode root){
            if(root == null){
                return 0;
            }
            int left = helper(root.left);
            int right = helper(root.right);
            //max有以下几种可能的取值,左子树路径和、右子树路径和、根节点单独或者是当前整棵树。
            max = Math.max(max, Math.max(Math.max(left,right) + root.val, Math.max(root.val, root.val + left + right)));
            //我们需要返回当前最长的一条路径给上一层递归,用于判断上一层的子树。
            return Math.max(Math.max(left,right) + root.val, root.val);
        }
    }

    我自己的想法和当时看的那个评论差不多,但是要复杂了,因为没有剪枝的操作,在判断max的时候需要多重Math.max套娃,代码可读性比较差。

  • 相关阅读:
    P3952 [NOIP2017 提高组] 时间复杂度
    1905. 统计子岛屿
    1102 Invert a Binary Tree (25 分)
    P1077 [NOIP2012 普及组] 摆花
    P3915 树的分解
    P1045 [NOIP2003 普及组] 麦森数
    P4961 小埋与扫雷
    P1123 取数游戏
    P1460 [USACO2.1]健康的荷斯坦奶牛 Healthy Holsteins
    CF1059B Forgery
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/12721042.html
Copyright © 2011-2022 走看看