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.

    对于每个结点,我们需要比较三个值。

    • 左结点为结尾的路径和+当前结点值
    • 右结点为结尾的路径和+当前结点值
    • 当前结点值

    取这个三个值作为以当前节点为结尾的最大路径和返回。

    同时获取以当前结点为根的子树的最大路径和,其子树最大路径来源于

    • 以当前结点为结尾的最大路径和(也就是上面结点所述的值)
    • 左节点为结尾的路径和+当前结点值+右结点为结尾的路径和
    • 左子树的最大路径和
    • 右子树的最大路径和

    取其4个值中得最大值作为子树的最大路径和。

    class Solution {
    public:
        int maxSum = INT_MIN;
        int getMaxSum(TreeNode* root){
            if(root == NULL) return 0;
            int leftSum = getMaxSum(root->left), rightSum = getMaxSum(root->right);
            int curSum =  max(root->val, max(root->val+leftSum, root->val+rightSum));
            maxSum = max(maxSum,max(curSum,root->val+leftSum+rightSum));
            return curSum;
        }
    
        int maxPathSum(TreeNode *root){
            getMaxSum(root);
            return maxSum;
        }
    };
  • 相关阅读:
    Zabbix 3.2.1 安装 Graphtree3.0.4 或 Graphtree3.2.x
    jquery-1
    AngularJS (1)
    css-2 (Text Font)
    css
    Java经验
    js经验
    mysql经验
    MySQL 函数
    jquery 效果
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3819070.html
Copyright © 2011-2022 走看看