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

Binary Tree Maximum Path Sum

时间:2015-01-27 22:01:36      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

求树的一点到另一点的最大路径,利用递归的方法,ans 在 左子树,右子树,root+左+右的最大中产生。

/**
 * 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 maxPathSum(TreeNode *root) {
      ans = INT_MIN;
      travel(root);
      return ans;
    }
    int travel(TreeNode * root){
        if(root == NULL) return 0;
        int sum = root->val;
        int leftsum = travel(root->left);
        int rightsum = travel(root->right);
        if(leftsum > 0) sum += leftsum;
        if(rightsum > 0) sum += rightsum;
        ans = max(ans,sum);
        sum = max(leftsum,rightsum);
        return root->val + (sum > 0 ? sum : 0);
    }
};   



Binary Tree Maximum Path Sum

标签:

原文地址:http://blog.csdn.net/sina012345/article/details/43200851

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