|
| 1 | +// 124. Binary Tree Maximum Path Sum |
| 2 | +/** |
| 3 | + * Given a binary tree, find the maximum path sum. |
| 4 | + * |
| 5 | + * 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. |
| 6 | + * |
| 7 | + * For example: |
| 8 | + * Given the below binary tree, |
| 9 | + * |
| 10 | + * 1 |
| 11 | + * / \ |
| 12 | + * 2 3 |
| 13 | + * Return 6. |
| 14 | + * |
| 15 | + * Tags: Tree, Depth-first Search |
| 16 | + * |
| 17 | + * Author: Kuang Qin |
| 18 | + */ |
| 19 | + |
| 20 | +#include "stdafx.h" |
| 21 | +#include <windows.h> |
| 22 | + |
| 23 | +using namespace std; |
| 24 | + |
| 25 | +/** |
| 26 | + * Definition for a binary tree node. |
| 27 | + */ |
| 28 | +struct TreeNode { |
| 29 | + int val; |
| 30 | + TreeNode *left; |
| 31 | + TreeNode *right; |
| 32 | + TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 33 | +}; |
| 34 | + |
| 35 | +class Solution { |
| 36 | + int curMax; |
| 37 | + |
| 38 | +public: |
| 39 | + int maxPathSum(TreeNode* root) { |
| 40 | + curMax = INT_MIN; |
| 41 | + dfs(root); |
| 42 | + return curMax; |
| 43 | + } |
| 44 | + |
| 45 | +// if we look at each individual nodes, there are only 3 possiblities: |
| 46 | +// a) Left branch: root->val + left |
| 47 | +// b) Right branch: root->val + right |
| 48 | +// c) Both branches: root->val + left + right |
| 49 | +// |
| 50 | +// a) or b): it can be accumulated between different nodes, so we use them as the return value in the recursion |
| 51 | +// c): it can be only a local maximum, so we compare it to the global maximum and keep whichever is larger |
| 52 | + |
| 53 | + int dfs(TreeNode* root) { |
| 54 | + if (!root) return 0; |
| 55 | + |
| 56 | + int left = max(dfs(root->left), 0); // if left child val < 0, keep only the parent node value |
| 57 | + int right = max(dfs(root->right), 0); // if right child val < 0, keep only the parent node value |
| 58 | + curMax = max(curMax, root->val + left + right); // compare the global max to possible local max |
| 59 | + |
| 60 | + return root->val + max(left, right); // choose whichever is larger |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | +int _tmain(int argc, _TCHAR* argv[]) |
| 65 | +{ |
| 66 | + return 0; |
| 67 | +} |
| 68 | + |
0 commit comments