One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as
#
.For example, the following binary tree
9 / \ 3 2 / \ / \ 4 1 6 #
can be serialized to the string
"9,3,4,#,#,1,#,#,2,6,#,#"
Given a string of comma-separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Assumes each comma-separated value can only be an integer or a character
'#'
. Valid input contains no spaces.Example 1:
Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true
Example 2:
Input: preorder = "1,#" Output: false
Example 3:
Input: preorder = "9,#,#,1" Output: false
Is it possible to have a completely empty tree serialized string? No, as the problem states all input strings are valid serializations of a binary tree, not empty.
What kind of values can nodes take?
Nodes can either be integers or the sentinel value #
.
Is there any constraint on the length of the input string? Typically, constraints would be provided in the broader problem description, but for this problem, we’ll assume a reasonable length.
The goal is to check the validity of a preorder serialized string of a binary tree. Here is a step-by-step strategy:
Initialization:
Initialize slots
to 1. This represents the number of slots available to place nodes. Initially, we have one slot — the root.
Iterate through Nodes: Split the input string by commas and iterate through the elements:
#
, it will create two additional slots (left and right children).Final Check: After processing all nodes, we should have exactly zero slots left. If we have extra slots, the preorder string is not valid.
Here’s a Python implementation based on the above strategy:
def isValidSerialization(preorder: str) -> bool:
nodes = preorder.split(',')
slots = 1 # we begin with one slot available (the root)
for node in nodes:
slots -= 1 # each node needs one slot
if slots < 0:
return False
if node != '#':
slots += 2 # non-null node generates two additional slots
return slots == 0
# Example usage:
preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
print(isValidSerialization(preorder)) # Output: True
Time Complexity: O(N), where N is the number of nodes (or the length of the input string split by commas).
This is because we are iterating through each node exactly once.
Space Complexity: O(N), due to the space used for storing split nodes. However, we do not use additional space proportional to tree size beyond the splitting process.
Feel free to ask for any further clarifications or additional test cases!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?