GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/src/VerifyPreorderSerialization.java at master · LeBW/leetcode

Expand file tree

/

VerifyPreorderSerialization.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
39 lines (39 loc) · 1.29 KB
/

VerifyPreorderSerialization.java

Copy path

File metadata and controls

39 lines (39 loc) · 1.29 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
36
37
38
39
/**
* 331. Verify Preorder Serialization of a Binary Tree
* 用栈的思想,记录树里可以插入的位置。
* 设 slot = 1, 表示一开始,树里有一个可以插入的地方。
* 然后,遍历节点:
* 1. 如果遇到的是 #,那么减少一个 slots
* 2. 如果遇到的是数字,那么首先减少一个slots,然后增加两个slots
*
* 最后,如果slots刚好为0,说明是有效的;否则是无效的。
* @author LBW
*/
public class VerifyPreorderSerialization {
public boolean isValidSerialization(String preorder) {
int slots = 1;
int idx = 0;
String s = preorder;
for (; idx < s.length(); idx++) {
if (s.charAt(idx) == ',')
continue;
if (s.charAt(idx) == '#') {
if (slots > 0)
slots -= 1;
else
return false;
}
else {
if (slots == 0)
return false;
int num = 0;
while (idx < s.length() && s.charAt(idx) >= '0' && s.charAt(idx) <= '9') {
num = num * 10 + s.charAt(idx) - '0';
idx += 1;
}
slots += 1;
}
}
return slots == 0;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.