利用先序递归法将二叉树转换为字符串
static char stringtree[500]={'\0'};//定义一个全局变量字符串 static int k=0;//标记字符串的当前位置 void string_tree(struct TreeNode* root){ if(NULL == root){//表示递归到NULL标记这个位置为#并记录一个, stringtree[k++]='#'; stringtree[k++]=','; return; } int d=root->val;//存储当前数结点值 if(d>=100){//当值大于等于100小于等于150的情况 stringtree[k++]=49; stringtree[k++]=d/10%10+48; stringtree[k++]=d%10+48; } else if(d>10){//当值小于100大于等于10的情况 stringtree[k++]=d/10+48; stringtree[k++]=d%10+48; } else{//当值小于10的情况 stringtree[k++]=d+48; } stringtree[k++]=',';//标记当前值结束 //先序遍历 string_tree(root->left); string_tree(root->right); } char* Serialize(struct TreeNode* root ) {//主函数 // write code here string_tree(root);//创建字符串 return stringtree;//返回字符串 }同理,用递归先序法将字符串转换为一个树
static int c=0;//标记字符串的位置 struct TreeNode* Deserialize(char* str ) { if(*(str+c) == '#'){//当字符串遇到#时将当前结点返回空 c+=2;//标记值加2,表示越过#和, return NULL; } struct TreeNode* root=(struct TreeNode*)malloc(sizeof(struct TreeNode));//给每个新节点创建新空间 root->val=0;//假设当前值为0,方便后续计算 while(*(str+c)!=','){//当遇到,时表示当前结点值计算完毕 root->val=root->val*10+*(str+c)-48; c++; } c++;//过滤,位 //先序遍历 root->left=Deserialize(str); root->right=Deserialize(str); return root; }