【61】序列化二叉树

    xiaoxiao2025-03-02  8

    【61】序列化二叉树

    参与人数:1703时间限制:1秒空间限制:32768K

    题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 牛客网题目链接:点击这里


    VS2010代码:

    // Source: http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&tqId=11214&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking // Author: Yang Qiang // Date : 2016-8-13 #include<iostream> #include<vector> //#include<string> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; class Solution { //前序遍历 void PreOrder(TreeNode *root,vector<int> &nums) { if(!root) { nums.push_back('$'); return; } else { nums.push_back(root->val); } PreOrder(root->left, nums); PreOrder(root->right,nums); } TreeNode* CreatBT(int* &ptr) { if(*ptr=='$') { ptr++; return NULL; } TreeNode* result1=new TreeNode(*ptr); ptr++; result1->left=CreatBT(ptr); result1->right=CreatBT(ptr); return result1; } public: char* Serialize(TreeNode *root) { //用新开的空间存储字符串。前序遍历一棵树 vector<int> nodes; nodes.clear(); PreOrder(root,nodes); int *res=new int[nodes.size()]; for(unsigned int i=0; i!=nodes.size(); i++) { res[i]=nodes[i]; } return (char*)res; } TreeNode* Deserialize(char *str) { //str是和自己定义的格式一样 int *p=(int*)str; TreeNode* result=NULL; result=CreatBT(p); return result; } };

    牛客网通过

    转载请注明原文地址: https://ju.6miu.com/read-1296811.html
    最新回复(0)