124. Binary Tree Maximum Path Sum (Tree; DFS)

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.

思路:存在val小于零的情况,所以path不一定是从叶子节点到叶子节点;每个节点存储以它为跟节点、和最大的路径,这个值依赖于左右子树=>后序遍历

/**
 * 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) {
        maxPath = INT_MIN;
        postOrderTraverse(root);
        return maxPath;
    }
    
    int postOrderTraverse(TreeNode* root){ 
        if(root==NULL) return 0;
        int left, right, sum;
        left = postOrderTraverse(root->left);
        right = postOrderTraverse(root->right);
        left = max(left,0); //ignore negative value
        right = max(right,0);
        sum = left + right +root->val;
        if(sum > maxPath) maxPath = sum;
        return root->val+max(left,right);//return current maximum sum from one child branch to root
    }
private: 
    int maxPath;
};

 

posted on 2015-10-04 11:17  joannae  阅读(222)  评论(0编辑  收藏  举报

导航