The maximum path sum in the binary tree and a worthy path in the binary tree

Insert picture description here

Idea: The
specific idea is also in the code, that is, to see how much value the left and right nodes can contribute, some code details have to be carefully considered.
Solution link!

Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    int dfs(TreeNode* root){
    
    
        if(root==NULL) return 0;
        // 递归计算左右子节点的最大贡献值
        // 只有在最大贡献值大于 0 时,才会选取对应子节点
        int left = dfs(root->left);
        int right = dfs(root->right);
        int cur = root->val;
         // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
        if(left>0) cur+=left;
        if(right>0) cur+=right;

        Max = max(Max,cur);
        // 返回节点的最大贡献值
        return max(root->val,max(left,right)+root->val);  //好好想想这句代码
        
    }
    int maxPathSum(TreeNode* root) {
    
    
        dfs(root);
        return Max;
    }
    int Max = -99999999;
};

Insert picture description here
Topic link!

Idea: This
question can be done according to the template of the pre-order traversal. We use a variable to record the value of each recursion, and use a vector to store the value of the node each time. When we reach the leaf node, we can see that it is It is not the target value. If it is, we will place it in the target vector; the most important point is that when backtracking, we must pop_bcak() the value encountered this time.

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:

    void dfs(TreeNode* root, int sum,vector<vector<int> >& q,int book,vector<int> &sk){
    
    
        book+=root->val;
        sk.push_back(root->val);
        bool ans =  (root->left==NULL  &&  root->right==NULL);
        if(ans && book==sum){
    
    
            q.push_back(sk);
        } 

        if(root->left!=NULL) dfs(root->left,sum,q,book,sk);
        if(root->right!=NULL) dfs(root->right,sum,q,book,sk);

        sk.pop_back();
        return ;
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
    
    
        vector<vector<int> >  q;
        if(root==NULL)  return q;
        vector<int> sk;
        dfs(root,sum,q,0,sk);
        return q;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/114850185