File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
docs/data-structure/stack Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -401,6 +401,44 @@ class MyStack:
401
401
return True
402
402
```
403
403
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
+
404
442
## 503. 下一个更大元素 II
405
443
406
444
[ 原题链接] ( https://leetcode-cn.com/problems/next-greater-element-ii/submissions/ )
You can’t perform that action at this time.
0 commit comments