码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_124_Binary Tree Maximum Path Sum

时间:2015-03-11 14:55:12      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   tree   dfs   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


124 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.


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
int max;
private:
    int DFS(TreeNode *root)
    {
        int left , right , value;
        if(root == NULL)
            return 0;
        left = DFS(root->left);
        right = DFS(root->right);
        value = root->val;
        if(left>0)
            value += left;
        if(right>0)
            value += right;
        if(value > max)
            max = value;
        if(left>right && left>0)
            return root->val + left;
        if(left<right && right>0)
            return root->val + right;
        return root->val;
    }
public:
    int maxPathSum(TreeNode *root) {
        max = -1000000;
        DFS(root);
        return max;
    }
};


leetcode_124_Binary Tree Maximum Path Sum

标签:c++   leetcode   tree   dfs   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/44197147

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!