自学内容网 自学内容网

LeetCode热题100刷题17:124. 二叉树中的最大路径和、437. 路径总和 III、199. 二叉树的右视图

124. 二叉树中的最大路径和

在这里插入图片描述

/**
 * 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 ans = -1001;
    int dfs(TreeNode* root,int& ans) {
        if(!root)
            return 0;
        int l_val = dfs(root->left,ans);
        int r_val = dfs(root->right,ans);
        ans = max(ans,l_val+r_val+root->val);
        return max(max(l_val,r_val)+root->val,0);
    }
    int maxPathSum(TreeNode* root) {
        
        dfs(root,ans);
        return ans;
    }
};

437. 路径总和 III

在这里插入图片描述

/**
 * 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 ans=0;
    unordered_map<long long, int> cnt{{0,1}};
    void backtracking(TreeNode* node, long long s, int targetSum) {
        if(!node) {
            return;
        }
        s+=node->val;
        ans += cnt.contains(s-targetSum) ? cnt[s-targetSum] : 0;
        cnt[s]++;
        backtracking(node->left,s,targetSum);
        backtracking(node->right,s,targetSum);
        cnt[s]--;
    }
    int pathSum(TreeNode* root, int targetSum) {
        backtracking(root,0,targetSum);
        return ans;
    }
};

199. 二叉树的右视图

在这里插入图片描述

/**
 * 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:
    vector<int> res;
    void dfs(TreeNode* node,int depth) {
        if(!node) {
            return;
        }
        if(depth==res.size())
            res.push_back(node->val);
        dfs(node->right,depth+1);
        dfs(node->left,depth+1);
    }
    vector<int> rightSideView(TreeNode* root) {
        dfs(root,0);
        return res;
    }
};

原文地址:https://blog.csdn.net/cir_sky/article/details/140535912

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!