Method One:
My own method, build a stack, each hit the number on the stack, every encounter #, will pop up a number, the last stack must be left a #.
1 Public Booleanisvalidserialization (String preorder) {2 if(Preorder = =NULL|| Preorder.length () = = 0) {3 return false;4 }5string[] res = Preorder.split (",");6stack<string> stack =NewStack<string>();7Stack.push (res[res.length-1]);8 for(inti = 0; i < res.length-1; i++) {9String each =Res[i];Ten if("#". Equals (each)) { One if(!Stack.isempty ()) { A Stack.pop (); -}Else { - return false; the } -}Else { - Stack.push (each); - } + } - return!stack.isempty () && Stack.peek (). Equals ("#"); +}
Time complexity is O (n)
2. Other people's methods
Each number can have two sides issued, each # will occupy an edge, each number itself will occupy an edge, but will produce two edges, so maintain a count, once less than 0 returns false.
Note that the following are:
1) This number initialization is 1, equivalent to a root node own 1 is 1, and produce two, so add up is 1;
2) Every time you encounter a number, you have to separate-1 and +2, if 1 is less than 0, return false
1 Public Booleanisvalidserialization (String preorder) {2string[] res = Preorder.split (",");3 intCount = 1;4 for(String each:res) {5 if(--count < 0) {6 return false;7 }8 if(!" #". Equals (each)) {9Count + = 2;Ten } One } A returnCount = = 0; -}
Time complexity is O (n)
Method Three:
Very good looking method, each leaf node structure is "number, #,#", so we put all of this format is replaced by a "#", constantly shrinking until the end should be a #.
1 Public Boolean isvalidserialization (String preorder) {2 String after = Preorder.replaceall ("\\d+,#,#", "#"); 3 return after.equals ("#") | | !after.equals (preorder) && isvalidserialization (after); 4 }
The third line, the reason is "!after.equals (preorder)", because such as an illegal tree "three-way", and there is no "number, #,#" Such a structure, so replaceall will not change it
Time complexity is O (n^2)
331. Verify preorder serialization of a Binary Tree