Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 603a0f7

Browse files
committed
🐱(stack): 331. 验证二叉树的前序序列化
1 parent eb7dc19 commit 603a0f7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/data-structure/stack/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,44 @@ class MyStack:
401401
return True
402402
```
403403

404+
## 331. 验证二叉树的前序序列化
405+
406+
[原题链接](https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree/)
407+
408+
### 解一:用栈辅助
409+
410+
按字符顺序依次入栈。如果入栈元素为 `#`,就判断栈顶能否凑成 `n##` 格式(`n` 为数字),如果可以就弹出 `n##`,让 `#` 入栈。因为 `n##` 表示一个叶节点,用 `#` 替代它以便让它的父节点达成叶节点条件(以此证明它是合法节点)。
411+
412+
```python
413+
class Solution:
414+
def isValidSerialization(self, preorder: str) -> bool:
415+
416+
stack = list()
417+
nodes = preorder.split(",")
418+
419+
for node in nodes:
420+
self.add_item(stack, node)
421+
# print(stack)
422+
423+
return True if len(stack) == 1 and stack[-1] == "#" else False
424+
425+
def add_item(self, stack, node):
426+
if node == "#":
427+
if len(stack) > 1:
428+
# 判断能否凑成 x##
429+
if stack[-1] == "#" and stack[-2] != "#":
430+
stack.pop()
431+
stack.pop()
432+
# 加入新的 #
433+
self.add_item(stack, "#")
434+
else:
435+
stack.append(node)
436+
else:
437+
stack.append(node)
438+
else:
439+
stack.append(node)
440+
```
441+
404442
## 503. 下一个更大元素 II
405443

406444
[原题链接](https://leetcode-cn.com/problems/next-greater-element-ii/submissions/)

0 commit comments

Comments
 (0)