K个一组链表翻转+前序中序构造二叉树

25. K 个一组翻转链表

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

image-20220426103601312

思路实现

  1. 先反转以 head 开头的 k 个元素
  2. 将第 k + 1 个元素作为 head 递归调用 reverseKGroup 函数
  3. 将上述两个过程的结果连接起来
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head == NULL) return head;
        auto a = head,b = head;
        for(int i = 0;i < k;i ++){
            if(b == NULL) return head;//不足k个不需要翻转
            b = b->next;
        }
        ListNode* newhead = reverse(a,b);
        a->next = reverseKGroup(b,k);
        return newhead;
    }
    //反转区间[a,b)的元素,注意是前闭后开
    ListNode* reverse(ListNode* a,ListNode* b){
        ListNode* pre = NULL;
        auto cur = a;
        while(cur != b){//类似单链表反转,迭代
            auto c = cur->next;
            cur->next = pre;
            pre = cur;
            cur = c;
        }
        return pre;
    }
};
105. 从前序与中序遍历序列构造二叉树

给定两个整数数组 preorderinorder ,其中 preorder 是二叉树的先序遍历inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

基本思路

构造二叉树,第一件事一定是找根节点,然后想办法构造左右子树image-20220426103943279

前序遍历结果第一个就是根节点的值,然后再根据中序遍历结果确定左右子树的节点。

image-20220426104010557

class Solution {
public:

    unordered_map<int,int> pos;//记录中序数组下标,方便定位根节点,和左右子树下标宽度

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for (int i = 0; i < n; i ++ )
            pos[inorder[i]] = i;
        return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
    }

    TreeNode* dfs(vector<int>&pre, vector<int>&in, int pl, int pr, int il, int ir)
    {
        if (pl > pr) return NULL;
        int k = pos[pre[pl]] - il;//左子树区间宽度
        TreeNode* root = new TreeNode(pre[pl]);
        //这里区间容易弄混,需要自己画图计算
        root->left = dfs(pre, in, pl + 1, pl + k, il, il + k - 1);
        root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir);
        return root;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值