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.

    后序遍历!

     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 myMax(int a, int b, int c) {
    13         a = a > b ? a : b;
    14         return a > c ? a : c;
    15     }
    16     
    17     int getMaxSum(TreeNode *root, int &max_sum) {
    18         if (root == NULL) {
    19             return 0;
    20         }
    21         int local_max = root->val;
    22         int left = getMaxSum(root->left, max_sum);
    23         int right = getMaxSum(root->right, max_sum);
    24         local_max += (left > 0) ? left : 0;
    25         local_max += (right > 0) ? right : 0;
    26         max_sum = max_sum > local_max ? max_sum : local_max;
    27         return myMax(root->val, root->val + left, root->val + right);
    28     }
    29     
    30     int maxPathSum(TreeNode *root) {
    31         int max_sum = INT_MIN;
    32         getMaxSum(root, max_sum);
    33         return max_sum;
    34     }
    35 };
  • 相关阅读:
    密码控件安全技术浅析及攻击实例
    一个QQ木马的逆向分析浅谈(附带源码)
    菜鸟开始学习SSDT HOOK((附带源码)
    leetcode229
    leetcode1401
    leetcode1400
    leetcode1399
    leetcode228
    leetcode223
    leetcode222
  • 原文地址:https://www.cnblogs.com/easonliu/p/3642942.html
Copyright © 2011-2022 走看看