首页 > 其他 > 详细

Leetcode 124

时间:2017-01-24 20:12:09      阅读:182      评论:0      收藏:0      [点我收藏+]

  原题链接

题目大意:

一棵节点带有点权的二叉树中,寻找最大节点和,感觉和XDU一题《ORZ系数之和》(用并查集实现)很像

/**
 * 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 maxPathSum(TreeNode* root){
        if(!root) return 0;
        int now=root->val;
        dfs(root,now);
        return now;
    }
    int dfs(TreeNode* root,int &now){
        if(!root) return 0;
        int res=root->val;
        int left=dfs(root->left,now);
        int right=dfs(root->right,now);
        if(left>0) res+=left;
        if(right>0) res+=right;
        if(res>now) now=res;
        return root->val+max(max(left,right),0);
    }
};

 

Leetcode 124

原文:http://www.cnblogs.com/freinds/p/6347702.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!