File tree Expand file tree Collapse file tree 1 file changed +12
-21
lines changed Expand file tree Collapse file tree 1 file changed +12
-21
lines changed Original file line number Diff line number Diff line change 1
1
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
+ }
23
12
}
13
+ return diff == 0 ;
14
+ }
24
15
}
You can’t perform that action at this time.
0 commit comments