Verify preorder serialization of a Binary Tree
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
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/
To determine whether the given sequence is a number ordinal traversal sequence.
The idea is to "dig holes", if the first is a number, that is the root node, it can be placed around 2 nodes, there are two "holes."
If it is ' # ', fill in a hole, and if it is a number, fill in a hole and add two holes.
When the hole is not enough or the final hole is not filled, it means that it is not sequential traversal sequence.
1 /**2 * @param {string} preorder3 * @return {Boolean}4 */5 varIsvalidserialization =function(preorder) {6 varspilted = Preorder.split (', '), holes = 0;7 if(Spilted.length = = 0)return true;8 if(Spilted[0]!== ' # ') holes + = 2;9 for(vari = 1; i < spilted.length; i++){Ten if(Spilted[i]!== ' # '){ One if(Holes > 0) holes++; A Else return false; -}Else{ -holes--; the } - if(Holes < 0)return false; - } - returnHoles = = = 0?true:false; +};
[Leetcode] [JavaScript] Verify preorder serialization of a Binary Tree