0
点赞
收藏
分享

微信扫一扫

剑指offer专项突击--第十七天

龙驹书房 2022-04-07 阅读 53
c++leetcode

剑指 Offer II 050. 向下的路径节点之和
空间换时间,用哈希表

class Solution {
public:
    unordered_map<int,int>mp;
    int ans=0;
    void dfs(TreeNode* root,int targetSum,int nowSum){
        mp[nowSum]++;
        if(mp[nowSum+root->val-targetSum]) ans+=(mp[nowSum+root->val-targetSum]);
        if(root->left) dfs(root->left,targetSum,nowSum+root->val);
        if(root->right) dfs(root->right,targetSum,nowSum+root->val);
        mp[nowSum]--;

    }
    int pathSum(TreeNode* root, int targetSum) {
        if(!root) return 0;
        dfs(root,targetSum,0);
        return ans;
    }
};

时间换空间
两层dfs

class Solution {
public:
    int pathSum(TreeNode* root, int targetSum) {
        travel(root,targetSum);
        return sum;
    }
    void travel(TreeNode* root,int targetSum) {
        if(!root) return;
        DFS(root,targetSum);
        travel(root->left,targetSum);
        travel(root->right,targetSum);
    }
    void DFS(TreeNode* root,int targetSum) {
        if(!root) return;
        int target = targetSum - root->val;
        if(root->val == targetSum) sum++;
        DFS(root->left,target);
        DFS(root->right,target);
    }
private:
    int sum = 0;
};

剑指 Offer II 051. 节点之和最大的路径
搜索每个子根节点来计算局部最大值,同时更新全局最大值

class Solution {
public:
    int ans_max =INT_MIN;
    int maxTree(TreeNode* root){
        if(!root) return 0;
        int left_max = max(maxTree(root->left),0);
        int right_max = max(maxTree(root->right),0);
        ans_max = max(ans_max,root->val+left_max+right_max);
        return root->val + max(left_max,right_max);
    }
    int maxPathSum(TreeNode* root) {
        maxTree(root);
        return ans_max;
    }
};

剑指 Offer II 052. 展平二叉搜索树
深搜即可

class Solution {
public:
    TreeNode* ans = new TreeNode();
    TreeNode* p = ans;
    void dfs(TreeNode* root){
        if(root->left) dfs(root->left);
        TreeNode* q = root;
        root->left = NULL;
        p->right = q;
        p = p->right;
        if(root->right) dfs(root->right);
    }
    TreeNode* increasingBST(TreeNode* root) {
        dfs(root);
        return ans->right;
    }
};
举报

相关推荐

0 条评论