[LeetCode] Binary Tree Maximum Path Sum

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.

Hide Tags
 Tree Depth-first Search
 
 
 

dfs,注意区分返回值和更新max_sum, 

注意,最后 return 的时候,只返回一个方向上的值,为什么?这是因为在递归中,只能向父节
点返回,不可能存在 L->root->R 的路径,只可能是 L->root 或 R->root。

就是说放回的时候返回L->root或者R->root,然后继续和root的parent相连接。

L->root->root's parent或者

R->root->root's parent 或者

root->root's parent (当L‘sum 和R’sum 都小于0的时候)

但是计算sum时是由 L->ROOT->R的路径的。

另外,节点的连通性是有遍历来保证的,能够遍历,那么必然能够联通

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
        int m_sum;
    public:
        int dfs(TreeNode * root)
        {   
            if(root == NULL)
                return 0;
            int l = dfs(root->left);
            int r = dfs(root->right);
            int sum = root->val;
            if(l > 0)  
                sum += l;
            if(r > 0)  
                sum += r;
#if 0
            cout << "l	" << l << endl;
            cout << "r	" << r << endl;
            cout << "root	" << root->val << endl;
            cout << "sum	" << sum<< endl;
#endif
            m_sum = max(m_sum, sum);

            if(max(l, r) > 0)
                return max(l, r) + root->val;
            else
                return root->val;
        }   


        int maxPathSum(TreeNode *root) 
        {   
            m_sum = INT_MIN;
            dfs(root);
            return m_sum;
        }
};
原文地址:https://www.cnblogs.com/diegodu/p/4422468.html