Skip to content

Commit 3f1afe8

Browse files
committed
Add solution #331
1 parent fcad07c commit 3f1afe8

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@
243243
322|[Coin Change](./0322-coin-change.js)|Medium|
244244
326|[Power of Three](./0326-power-of-three.js)|Easy|
245245
328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium|
246+
331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium|
246247
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|
247248
338|[Counting Bits](./0338-counting-bits.js)|Easy|
248249
342|[Power of Four](./0342-power-of-four.js)|Easy|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 331. Verify Preorder Serialization of a Binary Tree
3+
* https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null
7+
* node, we record the node's value. If it is a null node, we record using a sentinel value such
8+
* as '#'.
9+
*
10+
* For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#",
11+
* where '#' represents a null node.
12+
*
13+
* Given a string of comma-separated values preorder, return true if it is a correct preorder
14+
* traversal serialization of a binary tree.
15+
*
16+
* It is guaranteed that each comma-separated value in the string must be either an integer or
17+
* a character '#' representing null pointer.
18+
*
19+
* You may assume that the input format is always valid.
20+
* For example, it could never contain two consecutive commas, such as "1,,3".
21+
* Note: You are not allowed to reconstruct the tree.
22+
*/
23+
24+
/**
25+
* @param {string} preorder
26+
* @return {boolean}
27+
*/
28+
var isValidSerialization = function(preorder) {
29+
let result = 1;
30+
for (const node of preorder.split(',')) {
31+
if (result) {
32+
result += node === '#' ? -1 : 1;
33+
} else {
34+
return false;
35+
}
36+
}
37+
return result < 1;
38+
};

0 commit comments

Comments
 (0)