Skip to content

Commit e965a64

Browse files
authored
Create 331. Verify Preorder Serialization of a Binary Tree.java
1 parent 269dadf commit e965a64

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// NB:
2+
// - elements might contain more than 1 digit
3+
4+
public class Solution {
5+
public boolean isValidSerialization(String preorder) {
6+
ArrayList<String> list = new ArrayList<String>();
7+
String [] elems = preorder.split(",");
8+
9+
for (int i = 0; i < elems.length; i++) {
10+
list.add(elems[i]);
11+
12+
while (list.size() > 2
13+
&& list.get(list.size()-1).equals("#")
14+
&& list.get(list.size()-2).equals("#")
15+
&& !list.get(list.size()-3).equals("#")) {
16+
// remove the two nulls
17+
list.remove(list.size()-1); list.remove(list.size()-1);
18+
19+
// replace the last element with a null
20+
list.remove(list.size()-1); list.add("#");
21+
}
22+
}
23+
24+
return (list.size() == 1 && list.get(0).equals("#"));
25+
}
26+
}

0 commit comments

Comments
 (0)