The offer-binary tree and the deserialized binary tree-java of the sword finger

Source: Internet
Author: User

Topic Description :

Implement two functions to serialize and deserialize the binary tree, respectively.

Thinking Analysis :

Serialized binary tree, which can be traversed by the first order, first root node, then Zuozi, then the right subtree. Note that you want to use StringBuffer, because you can change the string directly, or if the root node is empty, then return "#" directly to the end. This is also the end sign of recursion.

Code :

Import Java.lang.StringBuffer;
Import java.lang.String;
    /* public class TreeNode {int val = 0;
    TreeNode left = null;

    TreeNode right = null;

    Public TreeNode (int val) {this.val = val;
    } */public class Solution {public int index=-1; String Serialize (TreeNode root) {stringbuffer s =new stringbuffer ();//stringbuffer thread-safe advantage if (root = null
        ) {S.append ("#,");//Ends Return s.tostring () with "#" and returns a string representation of the data in this sequence.
        S.append (root.val+ ",");/note is to put the value of the root node into StringBuffer s.append (Serialize (Root.left));//First left subtree after right subtree, this is the first sequence traversal method
        S.append (Serialize (root.right));
  return s.tostring ();//Returns a string representation of the data in this sequence.
        } TreeNode Deserialize (String str) {index++;
        string[] STRR = Str.split (","),//split with "," separated by the array int len = strr.length;
        if (index >= len) return null;
        TreeNode node = null;
     if (!strr[index].equals ("#")) {//array equal equals () is "#"       node = new TreeNode (integer.valueof (Strr[index]));
            Node.left = Deserialize (str);
        Node.right = Deserialize (str);
  } return node; }
}

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.