国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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));


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商河县| 和顺县| 宜章县| 静海县| 区。| 晴隆县| 吉木萨尔县| 六枝特区| 志丹县| 洪雅县| 土默特左旗| 顺平县| 社旗县| 栾城县| 兰考县| 阿荣旗| 五大连池市| 巴南区| 江川县| 河间市| 桂东县| 和静县| 万源市| 星子县| 南开区| 大冶市| 怀安县| 淄博市| 新河县| 石首市| 株洲县| 乌什县| 辽阳县| 苍南县| 雷波县| 洪湖市| 大英县| 磴口县| 北碚区| 容城县| 乌兰浩特市|