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

    1. Title

    Binary Tree Maximum Path Sum

    2. Http address

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

    3. The question

    Given a 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 does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

    Return 6.

    4. My code(AC)

     1     //DFS res[0] = sub tree max; res[1] = from root max;
     2     public static int []  maxPathSumTwoHelp(TreeNode root){
     3         
     4         int res [] = new int[2];
     5         int res_left[];
     6         int res_right[];
     7         
     8         if( root.left != null && root.right != null)
     9         {
    10             res_left = maxPathSumTwoHelp(root.left);
    11             res_right = maxPathSumTwoHelp(root.right);
    12             
    13             res[1] = Math.max(res_left[1], res_right[1]) + root.val;
    14             res[1] = Math.max(res[1], root.val);
    15             res[0] = Math.max(res_left[0], res_right[0]);
    16             res[0] = Math.max(res[0], res_left[1] + res_right[1] + root.val);
    17             res[0] = Math.max(res[0], res[1]);
    18             
    19         }else{
    20             if( root.left != null && root.right == null)
    21             {
    22                 res_left = maxPathSumTwoHelp(root.left);
    23                 res[1] =  Math.max(res_left[1] + root.val, root.val);
    24                 res[0] =  Math.max(res_left[0], root.val);
    25                 res[0] =  Math.max(res[0], res[1]);
    26             }else if( root.right != null &&  root.left == null)
    27             {
    28                 res_right = maxPathSumTwoHelp(root.right);
    29                 res[1] =  Math.max(res_right[1] + root.val, root.val);
    30                 res[0] =  Math.max(res_right[0], root.val);
    31                 res[0] =  Math.max(res[0], res[1]);
    32             }else{
    33                 res[0] = root.val;
    34                 res[1] = root.val;
    35             }
    36         }
    37         return res;
    38     }
    39     // Accepted
    40     public static int  maxPathSumTwo(TreeNode root){
    41         if( root == null)
    42             return 0;
    43         int res[] = maxPathSumTwoHelp(root); 
    44         return res[0];
    45     }
  • 相关阅读:
    Oracle手工建库
    php如何在某个时间上加一天?一小时? 时间加减
    JavaScript:this是什么?
    ping广播地址会如何(转)
    用CSS3实现文字描边
    vue二十七:vue基础之过滤器
    vue二十六:vue基础之vue生命周期
    vue二十五:vue基础之单个元素过渡和多个元素过渡
    vue二十五:vue基础之slot插槽和具名插槽
    vue二十四:vue基础之动态组件
  • 原文地址:https://www.cnblogs.com/ordili/p/4969971.html
Copyright © 2011-2022 走看看