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 };
  • 相关阅读:
    iSCSI又称为IPSAN
    文档类型定义DTD
    HDU 2971 Tower
    HDU 1588 Gauss Fibonacci
    URAL 1005 Stone Pile
    URAL 1003 Parity
    URAL 1002 Phone Numbers
    URAL 1007 Code Words
    HDU 3306 Another kind of Fibonacci
    FZU 1683 纪念SlingShot
  • 原文地址:https://www.cnblogs.com/easonliu/p/3642942.html
Copyright © 2011-2022 走看看