-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
35 lines (30 loc) · 973 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
// Binary Tree, String(Verify Preorder Serialization of a Binary Tree)
// https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/
// Created by hyungwook on 2022/05/05.
//
public class Solution {
public boolean isValidSerialization(String preorder) {
if (preorder.equals("#")) {
return true;
}
String[] splits = preorder.split(",");
int sentinelCount = 0;
for (int i = 0; i < splits.length; i++) {
String split = splits[i];
if (split.equals("#")) {
sentinelCount--;
if (sentinelCount < 0 || sentinelCount == 0 && i != splits.length - 1) {
return false;
}
} else {
if (i == 0) {
sentinelCount += 2;
} else {
sentinelCount += 1;
}
}
}
return sentinelCount == 0;
}
}