Binary Tree Maximum Path Sum

来源:互联网 发布:呼和浩特软件招聘信息 编辑:程序博客网 时间:2024/06/11 04:43

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.


Solution:

/** * 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) {        int maxSum = root ? root->val : 0;        dfs(root, maxSum);                return maxSum;    }        int dfs(TreeNode *root, int &maxSum)    {        if(!root) return 0;        int left = dfs(root->left, maxSum);        int right = dfs(root->right, maxSum);        maxSum = max(maxSum, root->val + max(left, 0) + max(right, 0));                return root->val + max(max(left, right), 0);    }};


0 0
原创粉丝点击