MediumNo. 0331
Verify Preorder Serialization of a Binary Tree — LeetCode 331 Python Solution
- Pattern
- Stack
- Topics
- Stack, Tree, String, Binary Tree
- Reading time
- 2 min
- Source
- leetcode.com
The problem
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value.
Example
- Input
- preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
- Output
- true
Python solution
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stk = []
for c in preorder.split(","):
stk.append(c)
while len(stk) > 2 and stk[-1] == stk[-2] == "#" and stk[-3] != "#":
stk = stk[:-3]
stk.append("#")
return len(stk) == 1 and stk[0] == "#"Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the length of the string `preorder`
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 331. Verify Preorder Serialization of a Binary Tree is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0094 | Binary Tree Inorder Traversal | Easy |
| 0114 | Flatten Binary Tree to Linked List | Medium |
| 0144 | Binary Tree Preorder Traversal | Easy |
| 0145 | Binary Tree Postorder Traversal | Easy |
| 0173 | Binary Search Tree Iterator | Medium |
| 0897 | Increasing Order Search Tree | Easy |
Frequently asked questions
- How hard is LeetCode 331. Verify Preorder Serialization of a Binary Tree?
LeetCode 331. Verify Preorder Serialization of a Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 331. Verify Preorder Serialization of a Binary Tree?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 331. Verify Preorder Serialization of a Binary Tree?
The Python solution on this page uses O(n), where n is the length of the string `preorder` auxiliary space.
- What topics does LeetCode 331. Verify Preorder Serialization of a Binary Tree cover?
LeetCode 331. Verify Preorder Serialization of a Binary Tree is tagged Stack, Tree, String and Binary Tree on LeetCode.