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

    这题比较难,没理顺关系,做了很多次还只是过了small judge,于是去看网上答案,然后再改了改,关键在于local_max和globe_max,globe_max要随时改得,而maxsum函数只是返回最大路径

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxSum(TreeNode * root, int & globe_max){  
    13         if(!root) {  
    14             return 0;  
    15         }  
    16         int local_max = root->val;  
    17         int left = maxSum(root->left, globe_max);  
    18         int right = maxSum(root->right, globe_max);  
    19         local_max = max(local_max, local_max+left);
    20         local_max = max(local_max, local_max+right);
    21         globe_max = max(globe_max, local_max);  
    22         return max(root->val, max(root->val+right, root->val+left) );  
    23     }  
    24     int maxPathSum(TreeNode *root) {
    25         // Start typing your C/C++ solution below
    26         // DO NOT write int main() function
    27         int globe_max = root->val;  
    28         int maxVal = maxSum(root, globe_max);  
    29         return max(globe_max, maxVal);  
    30     }
    31 };

     C#:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left;
     6  *     public TreeNode right;
     7  *     public TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int maxSum(TreeNode root, ref int globeMax)
    12     {
    13         if (root == null) return 0;
    14         int localMax = root.val;
    15         int left = maxSum(root.left, ref globeMax);
    16         int right = maxSum(root.right, ref globeMax);
    17         localMax = Math.Max(localMax, localMax + left);
    18         localMax = Math.Max(localMax, localMax + right);
    19         globeMax = Math.Max(globeMax, localMax);
    20         return Math.Max(root.val, Math.Max(root.val + left, root.val + right));
    21     }
    22     public int MaxPathSum(TreeNode root) {
    23         int globeMax = root.val;
    24         int maxVal = maxSum(root, ref globeMax);
    25         return Math.Max(globeMax, maxVal);
    26     }
    27 }
    View Code
  • 相关阅读:
    tfrecord汇总
    python2中的编码的问题
    python multiprocessing的问题
    转载,ubuntu shell ~/.bashrc /etc/bash.bashrc
    singleton模式 Python
    目标检测 tensorflow(预训练模型)
    functools.partial 小记
    python 踩坑小计 virtualenv-site-packages
    python3.6 _tkinter module问题 python源码重新编译
    windows核心编程之网络编程入门篇
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/2968756.html
Copyright © 2011-2022 走看看