|
| 1 | +/* |
| 2 | +Verify Preorder Serialization of a Binary Tree |
| 3 | +https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ |
| 4 | +
|
| 5 | +One way 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 #. |
| 6 | +
|
| 7 | + _9_ |
| 8 | + / \ |
| 9 | + 3 2 |
| 10 | + / \ / \ |
| 11 | + 4 1 # 6 |
| 12 | +/ \ / \ / \ |
| 13 | +# # # # # # |
| 14 | +For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. |
| 15 | +
|
| 16 | +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. |
| 17 | +
|
| 18 | +Each comma separated value in the string must be either an integer or a character '#' representing null pointer. |
| 19 | +
|
| 20 | +You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3". |
| 21 | +
|
| 22 | +Example 1: |
| 23 | +
|
| 24 | +Input: "9,3,4,#,#,1,#,#,2,#,6,#,#" |
| 25 | +Output: true |
| 26 | +Example 2: |
| 27 | +
|
| 28 | +Input: "1,#" |
| 29 | +Output: false |
| 30 | +Example 3: |
| 31 | +
|
| 32 | +Input: "9,#,#,1" |
| 33 | +Output: false |
| 34 | +*/ |
| 35 | + |
| 36 | +/** |
| 37 | + * @param {string} preorder |
| 38 | + * @return {boolean} |
| 39 | + */ |
| 40 | +var isValidSerialization = function(preorder) { |
| 41 | + if(preorder.length === 1 && preorder.charAt(0) === "#") |
| 42 | + return true; |
| 43 | + |
| 44 | + var depth = 0; |
| 45 | + var iter = 0; |
| 46 | + while(iter < preorder.length) { |
| 47 | + if(preorder.charAt(iter) === "#") { |
| 48 | + depth--; |
| 49 | + iter += 2 |
| 50 | + } else { |
| 51 | + while(iter < preorder.length && preorder.charAt(iter) !== ",") |
| 52 | + iter++ |
| 53 | + iter++; |
| 54 | + depth = (depth === 0) ? depth + 2 : depth + 1; |
| 55 | + } |
| 56 | + if(iter < preorder.length && depth === 0) |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + return depth === 0; |
| 61 | +}; |
| 62 | + |
| 63 | +var main = function() { |
| 64 | + console.log(isValidSerialization("")); |
| 65 | + console.log(isValidSerialization("#")); |
| 66 | + console.log(isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#")); |
| 67 | + console.log(isValidSerialization("9,#,92,#,#")); |
| 68 | + console.log(isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#")); |
| 69 | +} |
| 70 | + |
| 71 | +module.exports.main = main; |
0 commit comments