Leetcode--serialize and Deserialize Binary Tree

Source: Internet
Author: User

Description:

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

Design a algorithm to serialize and deserialize a binary tree. There is no restriction on what your serialization/deserialization algorithm should work. You just need to ensure, a binary tree can is serialized to a string and this string can is deserialized to the origin AL tree structure.

For example, serialize the following tree

    1   /  2   3      /     4   5

"[1,2,3,null,null,4,5]"as, just the same as how Leetcode OJ serializes a binary tree. You don't necessarily need to follow the this format, so that you are 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.

I thought the two-fork tree has brushed the comparison slipped, but still stepped on a variety of pits ...

The main idea is to serialize and deserialize the binary tree according to the corresponding rules. In fact, it is to find the binary tree "by layer" traversal sequence and according to the layer traversal sequence to find the binary tree. However, the per-layer traversal is locally symmetric, and if a node is not NULL, it must store its left and right child nodes, and if the child node is null, it is saved as "null". Note that his invocation is serialized and then deserialized if the same as the original tree is correct, so the intermediate returned sequence as long as the deserialization can parse the line, there is no fixed format.

Idea: Serialization is traversed by layers, and a queue is used to save the current node. Note that relative to the ordinary by-pass traversal, there is a condition can not be less, that is, can not use the queue as null as the loop termination condition, because the last leaf node of the left and right child nodes must be null, so that the serialized string will be more "null", need to add a number of valid nodes to determine the condition. If you do not want to use the condition that the queue is null as the only loop termination, you need to remove all of the last "null" from the sequence when deserializing.

AC Code:

1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten  Public classCodec { One  A     Private intCNT; -     //encodes a tree to a single string. -      PublicString serialize (TreeNode root) { the Nodecount (root); -StringBuilder res =NewStringBuilder (); -deque<treenode> queue =NewLinkedlist<treenode>(); -         if(Root = =NULL) { +             return NULL; -         } +          A Queue.offer (root); at         intCount = 0; -          while(Count < CNT &&!)Queue.isempty ()) { -              -TreeNode node =Queue.peek (); -             if(node = =NULL) { -Res.append ("null"); in Queue.poll (); -             } to             Else { +Res.append (Node.val + ""); -Count + +; the Queue.poll (); *                 if(Node.left! =NULL) { $ Queue.offer (node.left);Panax Notoginseng                 } -                 Else { theQueue.offer (NULL); +                 } A                 if(Node.right! =NULL) { the Queue.offer (node.right); +                 } -                 Else { $Queue.offer (NULL); $                 } -             } -              the         } -         returnres.tostring ();Wuyi     } the      -      Public inttreedepth (TreeNode root) { Wu         intDEP = 0; -         if(Root! =NULL) { About             intLEFTDP =treedepth (root.left); $             intRIGHTDP =treedepth (root.right); -DEP = LEFTDP&GT;=RIGHTDP? Leftdp+1:rightdp+1; -         } -         returnDEP; A     } +      the      -      Public voidnodecount (TreeNode root) { $         if(Root! =NULL) { theCNT + +; the Nodecount (root.left); the Nodecount (root.right); the         } -          in     } the  the     //decodes your encoded data to tree. About      PublicTreeNode Deserialize (String data) { the          the         if(Data = =NULL) { the             return NULL; +         } -          thedeque<string> queue =NewLinkedlist<string>();BayiDeque<treenode> Nodequeue =NewLinkedlist<treenode>(); thestring[] SpData = Data.split (""); the         inti = Spdata.length-1; -          while(Spdata[i].equals ("null")) i--; -          for(intj=0; j<=i; J + +) { the Queue.offer (Spdata[j]); the         } the          theTreeNode root =NewTreeNode (Integer.parseint (Queue.poll ())); -          the Nodequeue.offer (root); the          the          while(!Queue.isempty ()) {94TreeNode p =Nodequeue.poll (); theString LC =Queue.peek (); the             if(!Queue.isempty ()) { the Queue.poll ();98                 if(LC! =NULL) { About                     if(!lc.equals ("null")) { -TreeNode node =NewTreeNode (Integer.parseint (LC));101P.left =node;102 nodequeue.offer (node);103                     }104                 } the                 106             }107             108             if(!Queue.isempty ()) {109String rc =Queue.peek (); the Queue.poll ();111                 if(RC! =NULL) { the                     if(!rc.equals ("null")) {113TreeNode node =NewTreeNode (Integer.parseint (RC)); theP.right =node; the nodequeue.offer (node); the                     }117                 }118             }119         } -         returnRoot;121     }122 }123 124 //Your Codec object would be instantiated and called as such: the //Codec Codec = new Codec ();126 //Codec.deserialize (Codec.serialize (root));

Leetcode--serialize and Deserialize Binary Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.