Leetcode 剑指系列 Day 28 搜索与回溯

Leetcode 剑指系列 Day 28 搜索与回溯

1.剑指 Offer 37. 序列化二叉树

解题思路:

tree -> string 层序遍历

string -> tree 先将字符串分解并用其初始化节点保存入数组中,利用数组将各个节点连接起来

class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        if(root == nullptr) return res;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){
            TreeNode* temp = que.front();
            que.pop();
            if(temp != nullptr){
                res += to_string(temp->val);
                que.push(temp->left);
                que.push(temp->right);
            }
            else{
                res += "null";
            }
            if(!que.empty()) res += ",";
        }
        return res;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if(data.empty()) return nullptr;
        vector<TreeNode*> nodes;
        for(int l = 0, r = 0; r < data.size(); r++){
            //到了末尾将最后一个字符串提取出来
            if(r == data.size() - 1) r++;
            //当没遇到逗号之前都跳过
            if(r < data.size() && data[r] != ',') continue;
            //字符串转换成数字加入数组
            if(data.substr(l, r - l) == "null") nodes.push_back(nullptr);
            else {
                string temp = data.substr(l, r - l);
                nodes.push_back(new TreeNode(stoi(temp)));
            }
            l = r + 1;
        }
        int pos = 1; //利用pos寻找孩子节点
        for(int i = 0; i < nodes.size(); i++){
            if(nodes[i] == nullptr) continue;
            nodes[i]->left = nodes[pos++];
            nodes[i]->right = nodes[pos++];
        }
        return nodes[0];
    }
};

2.剑指 Offer 38. 字符串的排列

解题思路:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值