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

124. Binary Tree Maximum Path Sum (Tree; DFS)

时间:2015-10-04 12:18:38      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:存在val小于零的情况,所以path不一定是从叶子节点到叶子节点;

/**
 * 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) {
        maxSum = INT_MIN;
        calRootSum(root);
        
        return maxSum;
        
    }
    
    int calRootSum(TreeNode *root)
    {
        int leftSum = 0;
        int rightSum = 0;
        int sum;
        
        if(root->left) 
        {
            leftSum = calRootSum(root->left); //traverse left subtree
        }
        if(root->right) 
        {
            rightSum = calRootSum(root->right);//traverse right subtree
        }
        
        //val小于零的情况
        if(leftSum < 0) 
        {
            leftSum = 0;
        }
        if(rightSum < 0)
        {
            rightSum = 0;
        }
        
        sum = root->val+leftSum+rightSum;
        if(sum > maxSum)
        {
            maxSum = sum;
        }
        
        sum = root->val+max(leftSum,rightSum);
        return sum;
    }
private:
    int maxSum;
};

 

124. Binary Tree Maximum Path Sum (Tree; DFS)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4854355.html

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