序列化二叉树

题目描述:

使用任意一种遍历算法将二叉树拼成一个字符串,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);
			}
		}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值