• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
124. Binary Tree Maximum Path Sum *HARD* -- 二叉树中节点和最大的路径的节点和

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.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getMax(TreeNode* root, int &ans)
    {
        if(!root)
            return 0;
        int leftMax = getMax(root->left, ans), rightMax = getMax(root->right, ans), Max = max(leftMax, rightMax);
        int curMax = ((leftMax > 0) ? leftMax : 0) + ((rightMax > 0) ? rightMax : 0) + root->val;
        if(curMax > ans)
            ans = curMax;
        if(Max <= 0)
            return root->val;
        return Max + root->val;
    }
    int maxPathSum(TreeNode* root) {
        int ans = INT_MIN;
        getMax(root, ans);
        return ans;
    }
};

分别求左右子树的最大节点和,若为负,则忽略,若为正,则加上本身的节点值。

posted on 2016-04-21 11:15  ArgenBarbie  阅读(170)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3