leetcode 第124题 Binary Tree Maximum Path Sum

来源:互联网 发布:重庆时时彩杀号软件 编辑:程序博客网 时间:2024/06/06 01:29

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.

思路:用dfs遍历,先分别算出左右子树的和,若L>0,则加上L;若R>0,则加上R;最后比较root->val + max(L,R)和root->val哪个大,返回大的那个值;

C++实现:

/** * 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) {        max_sum = INT_MIN;        dfs(root);        return max_sum;    }private:    int max_sum;    int dfs(TreeNode* root){        if(root == NULL)            return 0;        int l = dfs(root->left);        int r = dfs(root->right);        int sum = root->val;        if(l > 0)            sum += l;        if(r > 0)            sum += r;        max_sum = max(max_sum,sum);        return max(l,r) > 0?root->val + max(l,r):root->val;    }};
0 0
原创粉丝点击