leetcode - 297. 二叉树的序列化与反序列化

leetcode - 297. 二叉树的序列化与反序列化

题目

leetcode - 297. 二叉树的序列化与反序列化_第1张图片

代码

#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef struct TreeNode{
	int val;
	struct TreeNode *left, *right;
}TreeNode, *BiTree;

string res = "";

void preInorder(TreeNode *root){
	if(!root){
		res += "null,";
		return;
	}
	res += to_string(root->val) + ","; 
	preInorder(root->left);
	preInorder(root->right);
}

string serialize(TreeNode* root) {	
	preInorder(root);
	return res;        
}

TreeNode* create(list<string> &array){
	if(array.front() == "null"){
		array.erase(array.begin());
		return NULL;
	}
	TreeNode *root = new TreeNode;
	root->val = stoi(array.front());
	array.erase(array.begin());
	root->left = create(array);
	root->right = create(array);
	return root; 
}

TreeNode* deserialize(string data) {
	list<string> array;
	string str = "";
	for(int i = 0; i < data.size(); i++){
		if(data[i] == ','){
			array.push_back(str);
			str = "";
		}else{
			str += data[i];
		}
	}
	if(str != ""){
		array.push_back(str);
	}	 
	return create(array);       
}

int main(){
	
	return 0;
}

你可能感兴趣的:(刷题,leetcode,c++,算法)