leetcode@ [124] Binary Tree Maximum Path Sum (DFS)

https://leetcode.com/problems/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 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 res = INT_MIN; int dfs(TreeNode* root) {
if(!root) return ; int l = dfs(root->left);
int r = dfs(root->right); int rhs = root->val;
if(l > ) rhs += l;
if(r > ) rhs += r;
res = max(res, rhs); return max(l, r) <= ? root->val: max(l, r) + root->val;
} int maxPathSum(TreeNode* root) {
if(!root) return ; dfs(root); return res;
}
};
上一篇:Javascript设计模式系列三


下一篇:WP8.1应用双击返回键退出程序。