Leetcode Serialize and Deserialize Binary Tree

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

Put a tree serialize and deserialize. The recursive method is serialize by pre-order.

    1   /   2   3     /     4   5

The example becomes the "1,2,#,#,3,4,#,#,5,#,#". Then deserialize reads a character as the root node, and then the left and right child nodes of the root node call the Deserializehelper function recursively.

Here Stringtokenizer:stringtokenizer st = new StringTokenizer (data, ",") can be used to separate data with "," to generate StringTokenizer.

StringTokenizer two Method:st.hasMoreTokens () returns whether tokens and St.nexttoken () return the next string. StringTokenizer is much like String.Split ().

But he can process the split string in the middle.

AC Java:

1  Public classCodec {2 3     //encodes a tree to a single string.4      PublicString serialize (TreeNode root) {5StringBuilder SB =NewStringBuilder ();6 Serializehelper (ROOT,SB);7         returnsb.tostring ();8     }9     Ten     Private voidserializehelper (TreeNode root, StringBuilder sb) { One         if(Root = =NULL){ ASb.append ("#,"); -             return; -         } theSb.append (Root.val). Append (","); - Serializehelper (Root.left, SB); - Serializehelper (Root.right, SB); -     } +  -     //decodes your encoded data to tree. +      PublicTreeNode Deserialize (String data) { AStringTokenizer st =NewStringTokenizer (data, ","); at         returnDeserializehelper (ST); -     } -      -     PrivateTreeNode Deserializehelper (StringTokenizer St) { -         if(!St.hasmoretokens ()) { -             return NULL; in         } -String cur =st.nexttoken (); to         if(Cur.equals ("#")){ +             return NULL; -         } theTreeNode root =NewTreeNode (integer.valueof (cur)); *Root.left =Deserializehelper (ST); $Root.right =Deserializehelper (ST);Panax Notoginseng         returnRoot; -     } the}

The iteration method uses the BFS. When processing serialize, queue is not empty, popup node cur, if cur is null, add "#," after SB; If it is not NULL, add Cur.val and "," after SB.

When processing deserialize, first string array with "," Gecheng string. If it is full tree, then the left node index is 2*i+1, the right node index is 2*i+2. But this is not full of trees.

It is necessary to record at the same time that there are several null nodes in front of the current I, with Count storage, the left node index into a (i-count[i]) + 1, the right node index into a (I-count[i]) + 2.

Note: Remember that the queue is an abstract class and cannot be used directly to generate que, it needs to be linkedlist.

AC Java:

1  Public classCodec {2 3     //encodes a tree to a single string.4      PublicString serialize (TreeNode root) {5StringBuilder SB =NewStringBuilder ();6Queue<treenode> que =NewLinkedlist<treenode> ();//Error7 Que.offer (root);8          while(!Que.isempty ()) {9TreeNode cur =Que.poll ();Ten             if(cur = =NULL){ OneSb.append ("#,"); A}Else{ -Sb.append (Cur.val). Append (","); - Que.offer (cur.left); the Que.offer (cur.right); -             } -         } -         returnsb.tostring (); +     } -  +     //decodes your encoded data to tree. A      PublicTreeNode Deserialize (String data) { atString [] s = Data.split (","); -         int[] Count =New int[s.length]; -TreeNode [] TNS =NewTreenode[s.length]; -          -          for(inti = 0; i<s.length; i++){ -             if(i>0){ inCount[i] = count[i-1]; -             } to             if(S[i].equals ("#")){ +Tns[i] =NULL; -count[i]++; the}Else{ *Tns[i] =NewTreeNode (integer.valueof (s[i)); $             }Panax Notoginseng         } -          the          for(inti = 0; i<s.length; i++){ +             if(S[i].equals ("#")){ A                 Continue; the             } +Tns[i].left = tns[2 * (i-count[i]) + 1]; -Tns[i].right = tns[2 * (I-count[i]) + 2]; $         } $         returnTns[0]; -     } -}

Reference this post: http://blog.csdn.net/ljiabin/article/details/49474445

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.