Binary tree and the maximum path

Leecode brush title

  • Title Description

Given a non-null binary tree, and return the maximum path.
In this problem, it is defined as a path from any node in the tree, to the sequence of any node. The path includes at least one node, and not necessarily through the root node.

  • Example
    Input: [1,2,3]

      1
     / \
    2   3
    

Output: 6

  • Code
/*最大值只有四种情况:节点, 节点及左树,节点及右树,左右树及节点。最后一种情况不能作为左右树继续递归,需要保存临时最大值*/
/**
 * 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) {
        if(root == NULL)
            return 0;
        int ans = INT_MIN;
        MaxSum(root,ans);
        return ans;
    }    
int MaxSum(TreeNode* root, int& ans)
{
        if(root == NULL)
            return 0;
        int left = max(0,MaxSum(root->left,ans));  
        int right = max(0,MaxSum(root->right,ans));
        ans = max(ans, left+right+root->val);
        return max(left+root->val,right+root->val);
    }
};

Guess you like

Origin blog.csdn.net/qq_42780025/article/details/91834212