Skip to content

Commit 8bd75fd

Browse files
authored
Update Verify Preorder Serialization of a Binary Tree.java
1 parent 869df5c commit 8bd75fd

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed
Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,15 @@
11
class Solution {
2-
public boolean isValidSerialization(String preorder) {
3-
Stack<String> stack = new Stack<>();
4-
String[] array = preorder.split(",");
5-
6-
for (String node : array) {
7-
if (node.equals("#")) {
8-
while (!stack.isEmpty() && stack.peek().equals("#")) {
9-
stack.pop();
10-
if (stack.isEmpty()) {
11-
return false;
12-
}
13-
stack.pop();
14-
}
15-
stack.push(node);
16-
}
17-
else {
18-
stack.push(node);
19-
}
20-
}
21-
22-
return stack.size() == 1 && stack.peek().equals("#");
2+
public boolean isValidSerialization(String preorder) {
3+
String[] nodes = preorder.split(",");
4+
int diff = 1;
5+
for (String node : nodes) {
6+
if (--diff < 0) {
7+
return false;
8+
}
9+
if (!node.equals("#")) {
10+
diff += 2;
11+
}
2312
}
13+
return diff == 0;
14+
}
2415
}

0 commit comments

Comments
 (0)