#331

Verify Preorder Serialization of a Binary Tree

Medium
StringStackTreeBinary TreeGreedyTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can achieve a more efficient solution by using a single pass through the nodes while maintaining a count of available slots for new nodes, which allows us to validate the preorder serialization in linear time.

⚙️

Algorithm

6 steps
  1. 1Step 1: Split the input string by commas to get a list of nodes.
  2. 2Step 2: Initialize a counter for available slots, starting with 1.
  3. 3Step 3: For each node in the list, decrement the slot count for the current node.
  4. 4Step 4: If the node is not a '#', increment the slot count by 2 (since it creates two new slots).
  5. 5Step 5: If at any point the slot count goes negative, return false.
  6. 6Step 6: After processing all nodes, return true if the slot count is zero.
solution.py10 lines
1def isValidSerialization(preorder):
2    nodes = preorder.split(',')
3    slots = 1
4    for node in nodes:
5        slots -= 1
6        if slots < 0:
7            return False
8        if node != '#':
9            slots += 2
10    return slots == 0

Complexity note: The time complexity is O(n) because we only pass through the list of nodes once, and the space complexity is O(n) due to the storage of the split nodes.

  • 1Each non-null node creates two new slots, while each null node consumes one slot.
  • 2The final count of slots must be zero for a valid serialization.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.