[Leetcode] 331. Verify preorder serialization of a Binary Tree Java

Source: Internet
Author: User

Topic:

One-to-serialize a binary tree is-to-use pre-order traversal. When we encounter a non-null node, we record the node ' s value. If It is a null node, we record using a Sentinel value such as # .

     _9_    /      3     2  /\   /  4   1  #  6/\/\   /#   # # # # # # # # #

For example, the above binary tree can "9,3,4,#,#,1,#,#,2,#,6,#,#" is serialized to the string, where # represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree . Find an algorithm without reconstructing the tree.

Each comma separated value in the string must is either an integer or a character ‘#‘ representing null pointer.

Assume that the input format is always valid, for example it could never contain, consecutive commas such as .

Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Returntrue

Example 2:
"1,#"
Returnfalse

Example 3:
"9,#,#,1"
Returnfalse

test instructions and analysis: a binary tree is given a pre-sequence traversal, which requires determining whether the two-fork tree is legal.

The first method : Observation can be learned that the structure of each leaf node is "number, #,#", so we have all such a format is replaced by a "#", constantly shrinking until the end should be a #. The code is as follows:

 Public classSolution { Public Booleanisvalidserialization (String preorder) {string[] strings=preorder.split (","); Booleanres=false; List<String> list=NewArraylist<>(); //the structure of each leaf node is "number, #,#", so we replace all such formats with a "#", shrinking until the end should be a #         for(inti=0;i<strings.length;i++) {String str=Strings[i];            List.add (str); //Shrinkage             while(List.size () >=3&&list.get (List.size ()-1). Equals ("#") &&list.get (List.size ()-2). Equals ("#") &&!list.get (List.size ()-3). Equals ("#") {List.remove (List.size () )-1); List.remove (List.size ()-1); List.remove (List.size ()-1); List.add ("#"); }        }                if(List.size () ==1&&list.get (0). Equals ("#")) Res=true; //System.out.println (res);        returnRes; }}

The second method:

In the process of construction, the difference between the degree and the degree of entry is recorded asdiff = outdegree - indegree

When traversing a node, we make diff-1 (because the node provides an entry). If diff<0, returns False if the node is not empty, and then diff + 2 (because the node provides 2 out-of-order).

Finally Judge Diff==0;

Understanding: If at some point during the traversal, the system's in > Out, then the "Idle branch" of all the branch nodes that have occurred in the current sequence is exhausted, and the post-order node has no way to mount to the previous node, thus determining that the sequence of sequential traversal is illegal.

The code is as follows:

public boolean isvalidserialization (String preorder) {        string[] res = Preorder.split (",");        int diff = 1;        for (String each:res) {            if (--diff < 0) {                return false;            }            if (! " # ". Equals (each)) {                diff + = 2;            }        }        return diff = = 0;    }

  

[Leetcode] 331. Verify preorder serialization of a Binary Tree Java

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.