/** 331. Verify preorder serialization of a Binary Tree * 2016-7-9 by Mingyang * This topic my absolutely original idea is to put number# #变为 #, so constantly the Russian block type of reduction * There is only one # left in the end, so do it yourself, then use the StringBuffer replace function * But found a case to pass, that is, "9,#,92,#,#" why? Just because I take the number of individual digit * into account, I don't see 92 as a whole. * then refer to the online stack practice, the same idea * There are also very clever gods, with the degree of the same as the degree to do, really is very good! */ //own initial approach Public Static Booleanisvalidserialization (String preorder) {intLen =preorder.length (); if(Preorder = =NULL|| Len = = 0) return true; Preorder= Preorder.replaceall (",", "" "); StringBuffer SB=NewStringBuffer (preorder); inti =sb.length (); while(I >= 3) { while(I > 2) { if(Sb.charat (i-1) = = ' # ' && sb.charat (i-2) = = ' # ' && sb.charat (i-3)! = ' # ') {Sb.replace (i-3, I, "#"); I=sb.length (); } Else{i--; } } Break; } if(Sb.tostring (). Equals ("#")) return true; return false; } //Stack's approach: Public BooleanIsValidSerialization1 (String preorder) {//using a stack, scan left to right//Case 1:we See a number, just push it to the stack//Case 2:we See #, check if the top of the stack is also #//if so, Pop #, pops the number in a while loop, until top of stack is//Not #//if not, push it to stack//in the end, check if stack size is 1, and Stack top is # if(Preorder = =NULL) { return false; } Stack<String> st =NewStack<>(); String[] STRs= Preorder.split (","); for(intpos = 0; POS < Strs.length; pos++) {String Curr=Strs[pos]; while(Curr.equals ("#") &&!st.isempty () &&St.peek (). Equals (Curr)) {St.pop (); if(St.isempty ()) {return false; } st.pop (); } st.push (Curr); } returnSt.size () = = 1 && st.peek (). Equals ("#"); } //The practice of out-of-degrees, into degrees: Public BooleanIsValidSerialization2 (String preorder) {string[] STRs= Preorder.split (","); intdegree =-1;//Root have no indegree, for compensate Init with-1 for(String str:strs) {degree++;//All nodes has 1 indegree (root compensated) if(Degree > 0) {//Total degree should never exceeds 0 return false; } if(!str.equals ("#")) {//Only non-leaf node has 2 outdegreedegree-= 2; } } returndegree = = 0; }
331. Verify preorder serialization of a Binary Tree