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));
新聞熱點
疑難解答