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