题目描述:
使用任意一种遍历算法将二叉树拼成一个字符串,NULL指针用符号代替。
思路:
使用前序遍历,中序遍历,后续遍历都能正常转换,关于深度遍历已经详细阐述,但是为空的地方(有的树没有左或者右子树),用符号代替,对于反序列化,要将一个字符串转换为一个二叉树,对应的特殊字符在二叉树中代表为空,首先要将前面二叉树转换成的字符串中的!去除,在遍历去除!后的字符串时,当遇到#(前面二叉树中为空的地方使用#代替),就为一个空接点,递归思路与将二叉树转化为字符串时相同。
代码(前序遍历):
class solution
{
public:
string Dfs(TreeNode* pRoot)
{
string result="";
string res="";
if(pRoot)
result=dfs1(pRoot);
else
return result;
}
void dfs1(TreeNode* pRoot)
{
if(pRoot==NULL)
{
string str="#!";
res+=str;
return;
}
else
{
string str=pRoot->data+"!";
res+=str;
}
dfs1(pRoot->left);
dfs1(pRoot->right);
}
}
代码(中序遍历):
class solution
{
public:
string Dfs(TreeNode* pRoot)
{
string result="";
string res="";
if(pRoot)
{
dfs1(pRoot);
return res;
}
else
return result;
}
void dfs1(TreeNode* pRoot)
{
if(pRoot==NULL)
{
res+= "#!";
return;
}
dfs1(pRoot->left);
res+=pRoot->data+"!";
dfs1(pRoot->right);
}
}
代码(后续遍历):
class solution
{
public:
string Dfs(TreeNode* pRoot)
{
string result="";
string res="";
if(pRoot)
{
dfs1(pRoot);
return res;
}
else
return result;
}
void dfs1(TreeNode* pRoot)
{
if(pRoot==NULL)
{
res+= "#!";
return;
}
dfs1(pRoot->left);
dfs1(pRoot->right);
res+=pRoot->data+"!";
}
}
反序列化(前序遍历:)
class solution
{
public:
TreeNode* Deserialize(string str)
{
TreeNode* temp;
size_t pos=str.find('!');
/*去除字符串中的!*/
for(int i=0;i<str.length()&&pos>0;i++)
{
str.erase(pos,1);//删除字符串中pos位置的元素
pos=str.find('!');//找到字符中第一个!的索引,如果没有返回-1
}
createTree(temp);
string strTreeNode=str;
}
void createTree(T)
{
/*当遍历到#符号时,说明节点为空,同时取字符串第二位到结尾所有字符*/
if(strTreeNode=='#')
{
strTreeNode=strTreeNode.substr(1);
T=NULL;
}
else
{
/*当遍历的不是#符号时,说明节点不为空,把该数据给当前节点的值,同时取字符串第二位到结尾所有字符*/
T->data=strTreeNode.front();
strTreeNode=strTreeNode.substr(1);
TreeNode* temp=T;
createTree(temp->left);
createTree(temp->right);
}
}
}