297. 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.

思路:

先序遍历输出二叉树,遇到空就输出null

再递归一下来吧字符串转化为树


程序:

class pointer {
	int pos = 0;
}
 

public class Codec {

	public String post(TreeNode root) {
		if(root == null) return "null,";
		else return Integer.toString(root.val)+","+post(root.left)+post(root.right);
	}

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
    	return post(root);
    }
    
    public TreeNode decode(String[] str, pointer p) {
    	if(str[p.pos].equals("null")) {
    		p.pos++;
    		return null;
    	}
    	else {
    		TreeNode rt = new TreeNode(Integer.parseInt(str[p.pos]));
    		p.pos++;
    		rt.left = decode(str, p);
    		rt.right = decode(str, p);
    		return rt;
    	}
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
    	String[] strs = data.split(",");
    	return decode(strs, new pointer());
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值