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

这篇博客探讨了三种不同的算法问题:1)寻找二叉树中从根节点到叶节点的和等于特定值的路径;2)找到节点之和最大的路径;3)将二叉搜索树展平为单调递增的链表。博主通过空间换时间的哈希表方法和两层深度优先搜索解决了路径和问题,并展示了如何寻找节点之和的最大路径。最后,博主还展示了如何递归地将二叉搜索树转换为单调递增链表。

剑指 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值