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套娃,代码可读性比较差。

  • 相关阅读:
    设计一个smartnic
    lshw
    VF PF Reset Tests
    iommu dmar 和虚拟机
    2019-10-31-win10-uwp-访问解决方案文件
    2019-10-31-win10-uwp-访问解决方案文件
    2019-8-31-dotnet-使用-Environment.FailFast-结束程序
    2019-8-31-dotnet-使用-Environment.FailFast-结束程序
    docker dead but pid file exists 问题
    java数据结构(二叉树)
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/12721042.html
Copyright © 2011-2022 走看看