Java教程

2021/8/29

本文主要是介绍2021/8/29,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

CCPC网络赛

一场笔试

刷三题

总结复盘最近所学的知识。

 

 看了八章和第九章的一部分。

一题leetcode

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string ans = "";
        if(root == NULL) return ans;
        queue<TreeNode*> Q;
        Q.push(root);
        while(!Q.empty()){
            TreeNode *T = Q.front(); Q.pop();
            if(T != NULL){
                ans += to_string(T -> val);
                ans += "*"; 
                Q.push(T -> left); Q.push(T -> right);
            }
            else ans += "NULL*";
        }
        cout << "str " << ans << endl;
        return ans;
    }

    // Decodes your encoded data to tree.
    void dfs(TreeNode * &root,string &data,int &l){
        queue<TreeNode**>Q;
        Q.push(&root);
        while(!Q.empty()){
            TreeNode **T = Q.front(); Q.pop();
            int len = 0;
            if(data[l] == 'N'){
                *T = NULL; l += 5;
            } else {
                int s = l;
                while(l < data.size() && ((data[l] >= '0' && data[l] <= '9') || data[l] == '-')){
                    l ++; len ++;
                }
                string str = data.substr(s,len);
                int n = atoi(str.c_str());
                while(l < data.size() && data[l] == '*') ++ l;
                *T = (TreeNode *)malloc(sizeof(TreeNode));
                (*T) -> val = n;
                (*T) -> left = (*T) -> right = NULL;

                Q.push(&((*T) -> left));
                Q.push(&((*T) -> right));

            }
        }
        
       
        
        return ;
    }

    TreeNode* deserialize(string data) {
        TreeNode *root = NULL;
        if(data.size() == 0) return root;
        int l = 0;
        dfs(root,data,l);
        return  root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));

  

这篇关于2021/8/29的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!