首页 > 代码库 > Leetcode 124

Leetcode 124

  原题链接

题目大意:

一棵节点带有点权的二叉树中,寻找最大节点和,感觉和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