Verify Preorder Serialization of a Binary Tree — LeetCode 331 Python Solution
MediumStackTreeStringBinary Tree
- Problem
- #331
- Pattern
- Stack
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the string `preorder` auxiliary |
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
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.