Binary Tree Maximum Path Sum

Q:

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.

 

A:

类似于dp,递归对子树进行处理的时候,要计算5点。

1:以左子树的根节点为尾的最大sum值

2:以右子树的根节点为尾的最大sum值

3:根据1和2求出以当前节点为尾的最大sum值

4:根据1和2求出当前子树中经过当前根节点的最大sum值

5:根据4不断更新整颗树的最大sum值。

OK,还是有点意思的。

struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
 public:
  int maxPathSum(TreeNode *root) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (!root) return 0;  
    max_sum_ = -0x0ffffffe;
    maxPathInternal(root);
    return max_sum_;
  }
 private:
  int maxPathInternal(TreeNode* root) {
    if (!root) return 0;
    int max_path = 0;
    int left_max_path = maxPathInternal(root->left);
    int right_max_path = maxPathInternal(root->right);
    int child_max_path = max(left_max_path, right_max_path);
    if (child_max_path > 0) {
      max_path = child_max_path + root->val;
    } else {
      max_path = root->val;
    } 
    int cur_max_sum = root->val;
    if (left_max_path > 0) cur_max_sum += left_max_path;
    if (right_max_path > 0) cur_max_sum += right_max_path;
    max_sum = max(max_sum, cur_max_sum);
    return max_path;
  } 
 private:
  int max_sum_;
};

 

posted @ 2013-06-17 17:24  dmthinker  阅读(116)  评论(0)    收藏  举报