Verify Preorder Serialization of a Binary Tree

medium tree stack string

Problem

Given a comma-separated preorder serialization of a binary tree using # for null, return true if it's a valid serialization.

Inputpreorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
Outputtrue
Slot counter starts at 1; tracking it through the stream lands exactly at 0.

def is_valid_serialization(pre):
    slots = 1
    for tok in pre.split(","):
        if slots == 0: return False
        slots += -1 if tok == "#" else 1
    return slots == 0
function isValidSerialization(pre) {
  let slots = 1;
  for (const tok of pre.split(",")) {
    if (slots === 0) return false;
    slots += tok === "#" ? -1 : 1;
  }
  return slots === 0;
}
class Solution {
    public boolean isValidSerialization(String pre) {
        int slots = 1;
        for (String tok : pre.split(",")) {
            if (slots == 0) return false;
            slots += tok.equals("#") ? -1 : 1;
        }
        return slots == 0;
    }
}
bool isValidSerialization(string pre) {
    int slots = 1;
    string tok;
    pre += ",";
    for (char ch : pre) {
        if (ch == ',') {
            if (slots == 0) return false;
            slots += tok == "#" ? -1 : 1;
            tok.clear();
        } else tok += ch;
    }
    return slots == 0;
}
Time: O(n) Space: O(1)