"Leetcode" Verify preorder serialization of a Binary Tree

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/

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 be serialized to the String " 9,3,4,#,#,1,#,#,2,#,6,#,# ", Where #  represents a null node.

given A string of comma separated values, verify whether it is a correct preorder traversal serializatio N of a binary tree. Find an algorithm without reconstructing the tree.

each Comma Separated value in the string must being either an integer or a character  ' # '  representing null  pointer.

you may assume", "the" input format was always valid, for example it could never contain, consecutive Commas such as " 1,,3 ".

example 1:
" 9,3,4,#,#,1,#,#,2,#,6,#,# "
Return true

example 2:
" 1,# "
Return false

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

Ideas:

Two # can back a stack, and finally if the stack is only one # then true otherwise false

Algorithm:

public boolean isvalidserialization (String preorder) {      stack<string> Stack = new stack<string> ();      String ps[] = Preorder.split (",");      for (int i = 0; i < ps.length; i++) {          stack.push (ps[i]);          while (!stack.isempty () && Stack.peek (). Equals ("#") && stack.size () >= 3                  && stack.get ( Stack.size ()-2). Equals ("#") &&!stack.get (Stack.size ()-3). Equals ("#")) {              stack.pop ();              Stack.pop ();              Stack.pop ();              Stack.push ("#");          }      }      return stack.size () = = 1 && stack.peek (). Equals ("#");  }  


"Leetcode" Verify preorder serialization of a 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.