Binary Tree Maximum Path Sum

来源:互联网 发布:nginx动静分离原理 编辑:程序博客网 时间:2024/06/06 06:07

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.


维护一个最大数,同时对于每一个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 maxPathSum(TreeNode *root) {        myMax=INT_MIN;        maxPathHelper(root);        return myMax;    }        int maxPathHelper(TreeNode *root){        if (!root)            return 0;        int l=max(0, maxPathHelper(root->left));        int r=max(0, maxPathHelper(root->right));        myMax= max(l+r+root->val, myMax);        return max(l,r)+root->val;    }    int myMax;};


0 0
原创粉丝点击