zoukankan      html  css  js  c++  java
  • [leetcode] Binary Tree Maximum Path Sum

    Given a binary tree, find the maximum path sum.

    The path may start and end at any node in the tree.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

    Return 6.

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

    思路:因为树节点的值有可能是负值,所以并不一定长度越长总和就越大。递归求解,对于当前节点,递归求出左右子树的最大和,然后在root.val, root.val + leftSum, root.val + rightSum, root.val + leftSum + rightSum四种情况下找出最大的更新max值,注意返回时必须包括root节点和其中一个子节点用于父节点组成路径,所以是在root.val, root.val + leftSum, root.val + rightSum中选取最大的返回。

    public class Solution {
    
        private int max = Integer.MIN_VALUE;
    
        public int maxPathSum(TreeNode root) {
            maxPath(root);
            return max;
        }
    
        private int maxPath(TreeNode root) {
            if (root == null)
                return 0;
            int leftSum = maxPath(root.left);
            int rightSum = maxPath(root.right);
            max = myMax(max, myMax(root.val, root.val + leftSum, root.val + rightSum, root.val + leftSum + rightSum));
    
            return myMax(root.val, root.val + leftSum, root.val + rightSum);
    
        }
    
        private int myMax(int... a) {
            int res = Integer.MIN_VALUE;
            for (int each : a) {
                if (each > res)
                    res = each;
            }
            return res;
        }
    
        public static void main(String[] args) {
            TreeNode root = new TreeNode(5);
            root.left = new TreeNode(1);
            root.right = new TreeNode(2);
            root.left.left = new TreeNode(3);
            root.left.right = new TreeNode(4);
            System.out.println(new Solution().maxPathSum(root));
        }
    
    }

    思路:如果左子树或者右子树返回值<0,我们用0代替。

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

    第三遍记录:

    思路不变,每次更新max的时候,max本身不要忘记了。 

  • 相关阅读:
    华为交换机配置NTP服务端/客户端
    利用shell简单监控网络设备的接口状态发出告警
    Linux下自动清理超过指定大小文件
    Kotlin进阶学习5
    Kotlin进阶学习4
    Kotlin进阶学习3
    大二暑假第一周学习总结
    Kotlin进阶学习2
    Kotlin进阶学习1
    Kotlin基础学习3
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3823379.html
Copyright © 2011-2022 走看看