zoukankan      html  css  js  c++  java
  • [Algo] 140. Maximum Path Sum Binary Tree III

    Given a binary tree in which each node contains an integer number. Find the maximum possible subpath sum(both the starting and ending node of the subpath should be on the same path from root to one of the leaf nodes, and the subpath is allowed to contain only one node).

    Assumptions

    • The root of given binary tree is not null

    Examples

       -5

      /    

    2      11

         /    

        6     14

               /

            -3

    The maximum path sum is 11 + 14 = 25

    Solution 1:

    /**
     * public class TreeNode {
     *   public int key;
     *   public TreeNode left;
     *   public TreeNode right;
     *   public TreeNode(int key) {
     *     this.key = key;
     *   }
     * }
     */
    public class Solution {
      int maxValue = Integer.MIN_VALUE;
      public int maxPathSum(TreeNode root) {
        // Write your solution here
        helper(root, 0);
        return maxValue;
      }
    
      private void helper(TreeNode root, int preSum) {
        if (root == null) {
          return;
        }
        int curSum = preSum < 0 ? root.key : root.key + preSum;
        maxValue = Math.max(maxValue, curSum);
        helper(root.left, curSum);
        helper(root.right, curSum);
      }
    }

    Solution 2:

    /**
     * public class TreeNode {
     *   public int key;
     *   public TreeNode left;
     *   public TreeNode right;
     *   public TreeNode(int key) {
     *     this.key = key;
     *   }
     * }
     */
    public class Solution {
      int maxValue = Integer.MIN_VALUE;
      public int maxPathSum(TreeNode root) {
        // Write your solution here
        helper(root);
        return maxValue;
      }
    
      private int helper(TreeNode root) {
        if (root == null) {
          return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        int curSum = root.key + Math.max(0, Math.max(left, right));
        maxValue = Math.max(maxValue, curSum);
        return curSum;
      }
    }
  • 相关阅读:
    阿里巴巴研究员叔同:云原生是企业数字创新的最短路径
    【OpenYurt 深度解析】边缘网关缓存能力的优雅实现
    K8s 原生 Serverless 实践:ASK 与 Knative
    一年增加 1.2w 星,Dapr 能否引领云原生中间件的未来?
    源码解读:KubeVela 是如何将 appfile 转换为 K8s 特定资源对象的
    绘本推荐
    油猴Tampermonkey
    lan蓝tern灯
    6岁叛逆期
    留白
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12425945.html
Copyright © 2011-2022 走看看