1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Binary Tree Maximum Path Sum

Posted on 2013-12-31 15:38  1957  阅读(162)  评论(0编辑  收藏  举报

从任意两个节点之间最大的一条路径...

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int ans;
    int search(TreeNode* root){
        if(root == nullptr) return 0;
        int left , right;
        left = INT_MIN; right = INT_MIN;
        //node
        if(root -> left == nullptr && root -> right == nullptr){
            if(root -> val > ans){
                ans = root -> val;
                return root -> val;
            } 
        }
        //left
        bool hasLeft = false;
        bool hasRight = false;
        if(root -> left != nullptr){
            left = search(root -> left);
            hasLeft = true;
        }
        //right
        if(root -> right != nullptr){
            right = search(root -> right);
            hasRight = true;
        }
        if(hasLeft && hasRight){
            if(left + right + root->val > ans){
                ans = left + right + root -> val;
            }
        }
        if(hasLeft){
            if(left + root -> val > ans){
                ans = left + root -> val;
            }
        }
        if(hasRight){
            if(right + root -> val > ans){
                ans = right + root -> val;
            }
        }
        if(root -> val > ans) ans = root -> val;
        int res = INT_MIN;
        if(hasLeft){
            res = left + root -> val;
        }
        if(hasRight){
            res = max(res , right + root -> val);
        }
        res = max(res , root -> val);
        return res;
    }
    int maxPathSum(TreeNode *root) {
        if(root == nullptr) return 0;
        //left + right + root -> ans
        //left + root -> go on
        //right + root -> go on
        //root -> go on
        ans = INT_MIN;
        search(root);
        return ans;
    }
};