Leetcode 124. Binary Tree Maximum Path Sum

来源:互联网 发布:java购物商城源码 编辑:程序博客网 时间:2024/06/05 15:12
  1. Binary Tree Maximum Path Sum

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 must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

   1  / \ 2   3

Return 6.

//递归时注意分清左右子树的最大单向路径和全局最大路径(可以从左子树到父亲节点再到右子树)/** * 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 help(TreeNode* root,int &m){        if(root==0){            return 0;        }        int left=help(root->left,m);        int right=help(root->right,m);        int ret=max(max(left,right),0)+root->val;        m=max(max(m,ret),left+right+root->val);        return ret;    }    int maxPathSum(TreeNode* root) {        if(root==0)            return 0;        int ret=root->val;        help(root,ret);        return ret;    }};