首页 > 学院 > 开发设计 > 正文

297. Serialize and Deserialize Binary Tree

2019-11-08 03:24:23
字体:
来源:转载
供稿:网友

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   5as "[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.

思路:刚开始按照题目说的,用层序遍历,TLE,应该是null叠加不必要的重复操作太多,改用DFS后AC

/* * DFS可以减少null的运算量 * 即:遇到null就不再对该子node操作,直接返回 *  * 注意:这里的DFS一个是把结果当做输入参数传入,适合于现在StringBuilder这样的 *  * 另一个DFS是把结果当做返回值传出,因为当做入参传入不起作用 * (形参和实参刚开始虽然指向同一个node,但是node = new TreeNode(Integer.valueOf(val))后,就指向不同的对象了) */public class Codec {    // Encodes a tree to a single string.    public String serialize(TreeNode root) {             	StringBuilder sb = new StringBuilder();    	serialize(root, sb);    	    	return sb.toString();    }    private void serialize(TreeNode root, StringBuilder sb) {		if(root == null) {			sb.append("null,");			return;		}				sb.append(root.val).append(",");		serialize(root.left, sb);		serialize(root.right, sb);	}	// Decodes your encoded data to tree.    public TreeNode deserialize(String data) {    	Queue<String> q = new LinkedList<String>(Arrays.asList(data.split(",")));        return deserialize(q);    }	private TreeNode deserialize(Queue<String> q) {		// 绝对不会出现Queue为空的情况,因为遇到null的时候已经返回了		String val = q.remove();		if("null".equals(val))	return null;				TreeNode node = new TreeNode(Integer.valueOf(val));		node.left = deserialize(q);		node.right = deserialize(q);				return node;	}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表