|
| 1 | +/* |
| 2 | +Verify Preorder Serialization of a Binary Tree |
| 3 | +============================================== |
| 4 | +
|
| 5 | +One way to serialize a binary tree is to use preorder 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 | +For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. |
| 8 | +
|
| 9 | +Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. |
| 10 | +
|
| 11 | +It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. |
| 12 | +
|
| 13 | +You may assume that the input format is always valid. |
| 14 | +
|
| 15 | +For example, it could never contain two consecutive commas, such as "1,,3". |
| 16 | +Note: You are not allowed to reconstruct the tree. |
| 17 | +
|
| 18 | +Example 1: |
| 19 | +Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" |
| 20 | +Output: true |
| 21 | +
|
| 22 | +Example 2: |
| 23 | +Input: preorder = "1,#" |
| 24 | +Output: false |
| 25 | +
|
| 26 | +Example 3: |
| 27 | +Input: preorder = "9,#,#,1" |
| 28 | +Output: false |
| 29 | +
|
| 30 | +Constraints: |
| 31 | +1 <= preorder.length <= 104 |
| 32 | +preorder consist of integers in the range [0, 100] and '#' separated by commas ','. |
| 33 | +*/ |
| 34 | + |
| 35 | +class Solution { |
| 36 | +public: |
| 37 | + int j; |
| 38 | + vector<string> arr; |
| 39 | + |
| 40 | + bool dfs() { |
| 41 | + if(j >= arr.size()) return false; |
| 42 | + |
| 43 | + if(arr[j] == "#"){ |
| 44 | + j++; |
| 45 | + return true; |
| 46 | + } |
| 47 | + |
| 48 | + j++; |
| 49 | + return dfs() && dfs(); |
| 50 | + } |
| 51 | + |
| 52 | + bool isValidSerialization(string s) { |
| 53 | + string curr = ""; |
| 54 | + arr = vector<string> (0); |
| 55 | + |
| 56 | + for (int i = 0; i <= s.size(); ++i) { |
| 57 | + if(i == s.size() || s[i] == ',') { |
| 58 | + arr.push_back(curr); |
| 59 | + curr = ""; |
| 60 | + } |
| 61 | + else curr += s[i]; |
| 62 | + } |
| 63 | + |
| 64 | + j = 0; |
| 65 | + return dfs() && j == arr.size(); |
| 66 | + } |
| 67 | +}; |
0 commit comments