zoukankan      html  css  js  c++  java
  • [leetcode]124. Binary Tree Maximum Path Sum二叉树最大路径和

    Given a non-empty binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    Example 1:

    Input: [1,2,3]
    
           1
          / 
         2   3
    
    Output: 6
    

    Example 2:

    Input: [-10,9,20,null,null,15,7]
    
       -10
       / 
      9  20
        /  
       15   7
    
    Output: 42

    思路

    dfs:

                2

             /       

            1         -3

    maxPath:  1 + 2 + 0 

    1. use maxPath to update result from all paths which is max path sum 

    2. divide a path into 3 parts:

    a. left path: from root to left side down to 0 or more steps

    b. right path: from root to right side down to 0 or more steps 

    c. cur root itself 

    3. maxPath = c + (a>0 ? a: 0 ) + (b > 0 ? b:0)

    这是一道关于BST和recursion的经典题,需要掌握

    最naive的想法是找到所有BST的path,返回max

    发现, 任意一条path都有一个顶点(位置最高点)

    我们用这个顶点来分解所有path

    这样,以任意一个点为顶点的path就分解为

    a. max_sum (左边path)

    b. max_sum (右边path)

    c. 顶点自己的value

    进一步,

    a + b + c 组成的人字形path的max path sum

         2
        /  
       1    -3

    dfs的return value :  2(顶点自己的value必须加上,无论正负) +  1 (正数贡献自己) + 0 (-3为负数不做贡献就是及时止损了)  = 3 

    跟 [leetcode]543. Diameter of Binary Tree二叉树直径 的思路基本一致。

    代码

     1 class Solution {
     2     public int maxPathSum(TreeNode root) {
     3         // corner case 
     4         if(root == null){return 0;}
     5          /* 要么用个global variable放在class下,要么用长度为1的一维数组来存。
     6             maxSum的value,可正可负,初始化为Integer.MIN_VALUE。
     7         */
     8         int[] maxPath = new int[]{Integer.MIN_VALUE};
     9         dfs(root, maxPath);
    10         return maxPath[0];
    11     }
    12     // 递归求以root为顶点所有直上直下的path中,path sum最大的一条值。没有U-turn的
    13     private int dfs(TreeNode root, int[]maxPath){
    14         // left > 0 benefit sum, add to sum; left < 0 will worsen sum, default 0 
    15         int left = root.left != null ? Math.max(dfs(root.left, maxPath), 0) : 0;
    16         int right = root.right != null ? Math.max(dfs(root.right, maxPath), 0) : 0;
    17         int cur = root.val + left + right;
    18         maxPath[0] = Math.max(maxPath[0], cur);
    19         return root.val  + Math.max(left, right);
    20     }   
    21 }

     

  • 相关阅读:
    POJ ACM题分类
    HDU 4438 Hunters (概率 & 期望)
    HDU 1042 N!
    HDU 1073 Online Judge
    PKU 1006 Biorhythms (中国剩余定理 * *)
    HDU 1047 Integer Inquiry
    HDU 2710 Max Factorv (素数模板 & 多种解法)
    HDU A + B Problem II 1002
    第6期(江西省吉安市永丰县)县长手机信箱工作简报(自吹自擂政绩,自圆其说)
    Send mail from ASP.NET using your gmail account
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810307.html
Copyright © 2011-2022 走看看