【剑指Offer】序列化二叉树
发布日期:2022-02-10 08:55:14 浏览次数:35 分类:技术文章

本文共 2380 字,大约阅读时间需要 7 分钟。

题目

请实现两个函数,分别用来序列化和反序列化二叉树。

示例: 

你可以将以下二叉树:

    1

   / \
  2   3
     / \
    4   5

序列化为 "[1,2,3,null,null,4,5]"

思路

使用队列+循环实现

本题主要还是对字符串的处理过程,使用stream对象来操作字符串,单独写一个读入处理的函数

代码

/** * 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) {        ostringstream ostr;        if(root == NULL){            return "";        }        queue
q; q.push(root); while(q.empty() != true){ TreeNode* p = q.front(); if(p == NULL){ ostr << "null," ; }else{ ostr << p->val << "," ; } if(p != NULL) q.push(p->left); if(p != NULL) q.push(p->right); q.pop(); } return ostr.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data=="")return NULL; istringstream istr(data); queue
q; TreeNode* root=new TreeNode; TreeNode **number=new TreeNode*; if(ReadStream (istr,number)){ root=number[0]; if(root == NULL) return NULL; q.push(root); }else return NULL; TreeNode *temp; while(!q.empty()){ temp=q.front(); q.pop(); if(temp == NULL) continue; if(ReadStream(istr,number)){ temp->left=number[0]; q.push(temp->left); } else break; if(ReadStream(istr,number)){ temp->right=number[0]; q.push(temp->right); } else break; } return root; } bool ReadStream(istringstream &istr,TreeNode **number){ string s; //getline(
<字符数组chs>
<读取字符的个数n>
<终止符>
) if(getline(istr,s,',')){ if(s=="null") number[0]=NULL; else number[0]=new TreeNode(stoi(s)); return true; } return false; }};// Your Codec object will be instantiated and called as such:// Codec codec;// codec.deserialize(codec.serialize(root));

 

转载地址:https://blog.csdn.net/hanmin822/article/details/105744449 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【剑指Offer】最长不含重复字符的子字符串
下一篇:【剑指Offer】字符串的排列

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月15日 18时44分28秒