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
1. Stack
classSolution { Public: BOOLIsvalidserialization (stringpreorder) {Stack<Char>Stk; BOOLIsnum =false; Preorder.push_back (',');//Dummy Tail for(Auto C:preorder) {if(c = ='#'){ //Absorb:search for pattern ' #, number ' backward while(!stk.empty () && stk.top () = ='#') {stk.pop ();//Pop ' # ' if(Stk.empty () | | stk.top () = ='#')return false;//pattern ' #,#,# 'Stk.pop ();//Pop ' number '} stk.push ('#');//replace ' number ' with ' # ' since it had been fully explored/validated}Else if(c = =','){ if(Isnum) Stk.push ('N');//indicate This is a number instead of using the real numberIsnum =false; }Else{isnum=true; } } returnStk.size () = =1&& stk.top () = ='#'; }};
2. No stack
classSolution { Public: BOOLIsvalidserialization (stringpreorder) { string& s =preorder; while(S.size () >=5) { BOOLFind_pattern =false; for(inti = s.size ()-1; i>=4; i--) { if(S[i] = ='#'&& s[i-2] =='#'&& s[i-4] !='#') {Find_pattern=true; intj = I4-1; /*find the start place of pattern*/ while(J >0&& S[j]! =',') j--; S.replace (J+1, I-j,"#");/*replace S[j+1, I] to "#"*/ Break;/*start a trun search from the end*/ } } if(!find_pattern) Break; } /*Boundary:empty Tree*/ return(s.size () = =1&& s[0] =='#'); }};
From right to left, if the (number, #,#) mode appears, replace it with a #. Finally, if only one # is legal, otherwise illegal.
331. Verify preorder serialization of a Binary Tree--Judging whether it is a valid sequence of first order