从一个字符串构造一颗二叉树
1 把一个string 转为 一个一维数组
2. 从一个一位数组构造一颗二叉树
leetcode 297. 二叉树的序列化与反序列化
#include<iostream>
#include<bitset>
#include<string>
#include<vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){} ;
};
vector<TreeNode* > stringToVector(string data)
{
vector<TreeNode *> vec;
if(data.size()==0)
return vec;
int i = 0;
int len = data.size();
while(i<len)
{
string str="";
while(i<len && data[i]!=',')
{
str.push_back(data[i]);
i++;
}
if(str=="null")
{
vec.push_back(nullptr);
}else{
vec.push_back(new TreeNode(stoi(str)));
}
i++;
}
}
void preOrder(TreeNode * root)
{
if(root==nullptr)
{
cout<<"null ";
return;
}
cout<<root->val<<" ";
preOrder(root->left);
preOrder(root->right);
}
int main()
{
string data = "5,1,4,null,null,3,6";
TreeNode* pNode = new TreeNode(5);
cout<<pNode->val<<endl;
vector<TreeNode*> vec = stringToVector(data);
//输出vector
for(auto &x:vec)
if(x==nullptr)
cout<<"null"<<" ";
else
cout<<x->val<<" ";
cout<<endl;
//用vector 构造一个树
int j =1;
for(int i = 0; i<vec.size(); i++)
{
if(vec[i]==nullptr)
continue;
if(j<vec.size())
vec[i]->left = vec[j++];
if(j<vec.size())
vec[i]->right = vec[j++];
}
//先序遍历这棵树
preOrder(vec[0]);
return 0;
}