139.Serialize and Deserialize Binary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5
as  "[1,2,3,null,null,4,5]" , just the same as  how LeetCode OJ serializes a binary tree . You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

分析:将二叉树进行序列化和反序列化。

方法1:层次遍历之后进行序列话然后进行反序列化。参见http://blog.csdn.net/ljiabin/article/details/49474445

方法2:先序遍历进行序列化和反序列化。

需要额外注意的地方:1.选中某种方式进行序列话和反序列化的时候要前后一致。2.在写代码的过程中要注意细节,让相同的代码尽量不要重复运行。

	  /**Encodes a tree to a single string.
	   * 按照层次遍历的方法序列化二叉树。
	   * @param root
	   * @return
	   */
    public String serialize(TreeNode root) {
    	StringBuilder sb = new StringBuilder();
		 List<TreeNode> list = new ArrayList<TreeNode>(10);
		 list.add(root);
		 /*当队列不为空时,依次把读到的元素的子节点加到队列中,然后在队列中删除该节点。一直重复直到队列为空*/
		 while(!list.isEmpty()){
			 TreeNode node = list.get(0);
			 list.remove(0);
			if(node != null){
				sb.append(node.val);
				list.add(node.left);
				list.add(node.right);
			}else{
				sb.append("#");
			}
			 sb.append(",");
		 }
		 return sb.substring(0,sb.length()-1);
    }

    

    /**
     * 按照层序遍历之后进行反序列化。
     * @param str
     * @return
     */
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String str) {
    	 if (str.isEmpty()) return null;
         
         String[] vals = str.split(",");
         int[] nums = new int[vals.length]; // 节点i之前null节点的个数
         TreeNode[] nodes = new TreeNode[vals.length];
         
         for (int i = 0; i < vals.length; i++) {
             if (i > 0) {
                 nums[i] = nums[i - 1];
             }
             if (vals[i].equals("#")) {
                 nodes[i] = null;
                 nums[i]++;
             } else {
                 nodes[i] = new TreeNode(Integer.parseInt(vals[i]));
             }
         }
         
         for (int i = 0; i < vals.length; i++) {
             if (nodes[i] == null) {
                 continue;
             }
             nodes[i].left = nodes[2 * (i - nums[i]) + 1];
             nodes[i].right = nodes[2 * (i - nums[i]) + 2];
         }
         
         return nodes[0];
    }

public int index = -1;
	String[] DLRseq;
	/**
	 * 采用先序遍历的方式序列化二叉树。
	 * @param root
	 * @return
	 */
	 public String serialize(TreeNode root) {
		 StringBuilder s = new StringBuilder();
			if (root == null) {
				return "#";
			}
			s.append(root.val + ",");
			s.append(serialize(root.left));
			s.append(",");
			s.append(serialize(root.right));
			return s.toString();
	    }

	    

	    /**
	     * 根据先序遍历的结果对二叉树进行反序列化
	     * @param str
	     * @return
	     */
	    // Decodes your encoded data to tree.
	    public TreeNode deserialize(String str) {
	    	if(index==-1){
	    		DLRseq = str.split(",");//要注意这个地方只需要让DLRseq拆分一次即可。
	    	}
	    	index++;
			int len = str.length();
			TreeNode root = null;
			if (index >= len || DLRseq[index].equals("#")) {
				return null;
			}else{			
				root = new TreeNode(Integer.valueOf(DLRseq[index]));
				root.left = deserialize(str);
				root.right = deserialize(str);
				return root;
			}
	    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值